Reputation: 1100
I have a requirement to create several UI buttons and want to initialize the border width of each of them as and when these buttons are created and organize them in the screen.
The Xcode swift editor has properties to configure several attributes of an UI button, but I don't see a way to set the border width. Another option is to do it through code like
button.layer.borderWidth = 1
But if I create n buttons I need to insert n outlet references to set the border width of each of them, which I don't want to do. Is there any easy solution so that once I have one button created with a given border width, then I can create replicas with copy-paste.
Upvotes: 1
Views: 3757
Reputation: 421
You can create custom class extend UIButton.
class BorderButton : UIButton {
init(frame: CGRect) {
super.init(frame: frame)
layer.borderWidth = 1
}
}
And more, you want to customize borderWidth value like this:
@IBDesignable
class BorderButton : UIButton {
@IBInsepctable borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
init(frame: CGRect) {
super.init(frame: frame)
borderWidth = 1
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
borderWidth = 1
}
}
Using @IBDesignable and @IBInspectable, you can set borderWidth value from storyboard.
Upvotes: 1
Reputation: 24572
You can do something like this programmatically.
for view in self.view.subviews
{
if view.isKindOfClass(UIButton)
{
view.layer.borderWidth = 1
}
}
Upvotes: 1