【问题标题】:Custom UIButton layoutSubviews() doesn't work unless super.layoutSubviews() is called除非调用 super.layoutSubviews(),否则自定义 UIButton layoutSubviews() 不起作用
【发布时间】:2016-02-23 23:54:50
【问题描述】:

代码:

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 确实设置了,但没有设置标题)

问题 2:我尝试将 layoutSubviews() 中的代码放入 drawRect() 中,但这不会改变 cornerRadius

【问题讨论】:

    标签: ios uibutton


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      UIButton 是一个 UIView,它有自己的 layoutSubviews 实现。您仍然希望确保调用代码并因此调用super.layoutSubviews()除了默认实现(不是代替),您还想设置cornerRadiustitle,因此您在调用super 之后添加该代码。

      如果你没有覆盖方法周期,在调用layoutIfNeeded时,默认会调用UIView中的layoutSubviews()。如果您覆盖它并且不要调用super.layoutSubviews(),那么您实际上只是删除了Apple 对该方法的实现。

      这与在 UIViewController 的子类中重写方法时应该调用 super.viewDidLoad() 的原因相同。

      【讨论】:

      • Rob 的回答是正确的——因为没有调用 super 的实现,所以 UIView 没有布局它的 UILabel 子视图。
      猜你喜欢
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多