[UIKit] Button의 title은 setTitle로 설정하자

 

결론부터 말하자면, button.titleLabel로 title을 설정하려고 하면 안 된다.

이유는 다음과 같다.  애플의 공식 문서를 보자면... 

Screenshot 2023-07-26 at 9.02.46 PM.png
https://developer.apple.com/documentation/uikit/uibutton/1623992-titlelabel

titleLabel 프로퍼티의 경우에는 텍스트 색깔이나 그림자 색깔을 변경하는 데 사용하면 안 된다.

그 대신, setTitleColor(_:for:)와 setTitleShadowColor(_:for:)를 이용하라고 말하고 있다.

또한! 내가 의문이었던 title은 공식 문서에서 label의 title을 변경하기 위해서는 setTitle(_:for:)을 연결하라고 되어 있더라. 

 

Button.titleLabel?.text = "title" 이런 식으로 button의 Title을 넣어주는 것과 Button.setTitle("title", for: .normal) 으로 넣어주는 것이 동일하게 동작하는 줄 알았는데 완전 의외였다.

 

iOS 13 이후 style이 적용되는 버튼들만 titleLabel?.text로 적용이 되지 않는 줄 알았는데, 현재 Xcode 내에서 실행해 보면 title 값은 바뀌지만, button의 외적인 영역에는 아예 구현이 되지 않는 것을 볼 수 있었다.

 

 

etc-image-1
titleLabel 프로퍼티를 이용하여 title을 바꿨을 때

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var firstButton: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        firstButton.titleLabel?.text = "title"
        guard let buttonText =  firstButton.titleLabel?.text else { return }
        print(buttonText)
        //firstButton.setTitle("title", for: .normal)
    }

    @IBAction func buttonTapped(_ sender: UIButton) {
        
    }
    
}

 

코드로 보면 이렇다.

위 사진에서 볼 수 있듯이 titleLabel을 바꾸어 주면 title의 값은 바뀌지만, 실제 버튼의 외관은 바뀌지 않는다.

코드 리뷰 받다가 멘토님께 여쭤보았을 때, 아마 특정 스타일이 적용되지 않은 default 스타일의 버튼이면 적용될 거라고 하셨는데 완전히 막힌 게 아닐까 싶다.

(저 버튼도 스타일이 적용된 게 아니라 디폴트이기 때문에...)

 

 

 

 

 

etc-image-2
setTitle을 이용하여 button의 title을 바꿨을 때

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var firstButton: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        firstButton.titleLabel?.text = "title"
//        guard let buttonText =  firstButton.titleLabel?.text else { return }
//        print(buttonText)
        firstButton.setTitle("title", for: .normal)
    }

    @IBAction func buttonTapped(_ sender: UIButton) {
        
    }
    
}

애초에 공식 문서로 하지 마! 라고 못 박아놔서 더 그런 것 같다.

글로 작성하니 얼마 안 되고 정말 간단하지만... ^_^ 어제 왤케 오래 삽질했는지 모르겠다.

아무튼! 버튼의 타이틀이든 타이틀의 색상 / 타이틀 그림자의 색상까지~~!!! 

모두 setTitle로 설정하도록 하자.

 

 

 

 

 

 

https://developer.apple.com/documentation/uikit/uibutton/1623992-titlelabel

 

titleLabel | Apple Developer Documentation

A view that displays the value of the property for a button.

developer.apple.com

https://stackoverflow.com/questions/29517166/difference-between-settitleforstate-and-titlelabel-text

 

Difference between setTitle:forState: and titleLabel.text

After looking over the internet and other SO questions(this one is great iOS: UIButton titleLabel -- does it do anything at all?), it is unclear to me what is the difference between these two, more

stackoverflow.com

https://stackoverflow.com/questions/4910446/ios-uibutton-titlelabel-does-it-do-anything-at-all

 

iOS: UIButton titleLabel -- does it do anything at all?

I want to make a UIButton with type UIButtonTypeCustom (for the shape). I want to assign the title using button.titleLabel because I need to specify the font. The following code looks like it sho...

stackoverflow.com

 

'iOS' 카테고리의 다른 글

[Swift] instance / Type  (0) 2023.08.01
[Swift] Enum  (0) 2023.07.30
[UIKit] UITableViewController  (0) 2023.07.27
[Swift] Date.formatted()  (2) 2023.07.27
[Error] UITapGestureRecognizer issue  (0) 2023.07.23