Custom UIButton layoutSubviews() doesn't work unless super.layoutSubviews() is called

爷,独闯天下 提交于 2021-01-28 14:26:59

问题


Code:

class ViewController: UIViewController{

    var button = CustomButton()

    override func viewDidLoad(){
        super.viewDidLoad()
        button.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(button)
        //add constraints and etc.
    }
}

class CustomButton: UIButton{
    override func layoutSubviews() {
        super.layoutSubviews()
        self.layer.cornerRadius = self.layer.frame.width * 0.5
        self.setTitle("abc", forState: .Normal)
    }
}

Question 1: how come I have to call super.layoutSubviews() for the setTitle() to work? (i.e. the cornerRadius does get set but not the title)

Question 2: I tried putting the code I have in layoutSubviews() in drawRect() but that doesn't change the cornerRadius.


回答1:


The UIButton contains a UILabel subviews to display its title. If you don't call super.layoutSubviews(), that child label doesn't get set up properly.




回答2:


UIButton is a UIView, which has its own implementation of layoutSubviews. You still want to make sure that code gets called and hence call super.layoutSubviews(). In addition to the default implementation (not instead of), you want to set the cornerRadius and title so you add that code after the call on super.

If you didn't override the method period, layoutSubviews() in UIView would be called by default when layoutIfNeeded is called. If you override it and don't call super.layoutSubviews() then you essentially just removed Apple's implementation of the method.

It's the same reason you should call super.viewDidLoad() when overriding a the method inside a subclass of UIViewController.



来源:https://stackoverflow.com/questions/35590676/custom-uibutton-layoutsubviews-doesnt-work-unless-super-layoutsubviews-is-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!