本文介绍了除非调用 super.layoutSubviews(),否则自定义 UIButton layoutSubviews() 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

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)
    }
}

问题 1:为什么我必须调用 super.layoutSubviews() 才能使 setTitle() 工作?(即 cornerRadius 确实设置了但没有设置标题)

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)

问题 2:我尝试将 layoutSubviews() 中的代码放在 drawRect() 中,但这并没有改变 cornerRadius.

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

推荐答案

UIButton 包含一个 UILabel 子视图来显示其标题.如果您不调用 super.layoutSubviews(),则该子标签无法正确设置.

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.

这篇关于除非调用 super.layoutSubviews(),否则自定义 UIButton layoutSubviews() 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 04:51