问题
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