Swfit

NumberOfLines 값 설정이 안될 때

GGShin 2022. 2. 28. 17:40

콜렉션뷰 카드 안에 들어가는 라벨의 NumberOfLines 를 0으로 설정했음에도

위 사진처럼 적용이 안되는 현상이 생겼다.

 

다행히 해결방법은 간단했다.

바로 라벨의 width와 height을 설정해주어야만 NumberOfLines가 적용되는 것이었다.

1
2
3
4
5
6
7
8
9
let commentLabel: UILabel = {
        let label = UILabel()
        label.textColor = .black
        label.font = UIFont(name: "NotoSerifKR-Regular", size: 15.0)
        label.textAlignment = .center
        label.numberOfLines = 0
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
cs

원래 코드는 라벨 자체의 크기는 설정해주지 않았었다. 

그래도 텍스트가 나오길래 제대로 나오나보다 생각을 했는데, 문장 길이가 길어지니 제대로 설정이 되지 않았다는 게

바로 티가 나버렸다.

그래서 width와 height을 적용해보았다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
    let commentLabel: UILabel = {
        let label = UILabel()
        label.textColor = .black
        label.font = UIFont(name: "NotoSerifKR-Regular", size: 15.0)
        label.textAlignment = .center
 
        label.widthAnchor.constraint(equalToConstant: 220).isActive = true
        label.heightAnchor.constraint(equalToConstant: 100).isActive = true
 
        label.numberOfLines = 0
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
cs

라벨의 크기가 설정되자 정상적으로 numberOfLines = 0이 적용되는 것을 볼 수 있었다.

훨씬 깔끔하고 예쁘다 ^-^

 

결론은, numberOfLines 가 적용이 되지 않으면 적용하고자 하는 대상의 width와 height이 설정되어 있는지 확인해 볼 것! 

 

[관련된 stackoverflow 질문과 답변]

https://stackoverflow.com/questions/50620964/numberoflines-not-working

 

numberOfLines not working

This is my code, and not working the numberOfLines. How can i fix it. let texts = UILabel() texts.frame.size.width = 100 texts.text = "

stackoverflow.com

 

반응형