I\'m building an app using swift in the latest version of Xcode 6, and would like to know how I can modify my button so that it can have a rounded border that I could adjust mys
You can use this subclass of UIButton to customize UIButton as per your needs.
visit this github repo for reference
class RoundedRectButton: UIButton {
var selectedState: Bool = false
override func awakeFromNib() {
super.awakeFromNib()
layer.borderWidth = 2 / UIScreen.main.nativeScale
layer.borderColor = UIColor.white.cgColor
contentEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
}
override func layoutSubviews(){
super.layoutSubviews()
layer.cornerRadius = frame.height / 2
backgroundColor = selectedState ? UIColor.white : UIColor.clear
self.titleLabel?.textColor = selectedState ? UIColor.green : UIColor.white
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
selectedState = !selectedState
self.layoutSubviews()
}
}
To do this job in storyboard (Interface Builder Inspector)
With help of IBDesignable
, we can add more options to Interface Builder Inspector for UIButton
and tweak them on storyboard. First, add the following code to your project.
@IBDesignable extension UIButton {
@IBInspectable var borderWidth: CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat {
set {
layer.cornerRadius = newValue
}
get {
return layer.cornerRadius
}
}
@IBInspectable var borderColor: UIColor? {
set {
guard let uiColor = newValue else { return }
layer.borderColor = uiColor.cgColor
}
get {
guard let color = layer.borderColor else { return nil }
return UIColor(cgColor: color)
}
}
}
Then simply set the attributes for buttons on storyboard.
Based on @returntrue answer I managed to implement it in Interface Builder.
To get round corners button using Interface Builder add a Key Path = "layer.cornerRadius"
with Type = "Number"
and Value = "10"
(or other value as required) in the "User Defined RunTime Attribute
" of the Identity Inspector
of the button.
@IBOutlet weak var button: UIButton!
...
I think for radius just enough this parameter:
button.layer.cornerRadius = 5
It is globally method for rounded border of UIButton
class func setRoundedBorderButton(btn:UIButton)
{
btn.layer.cornerRadius = btn.frame.size.height/2
btn.layer.borderWidth = 0.5
btn.layer.borderColor = UIColor.darkGray.cgColor
}
import UIKit
@IBDesignable
class RoundedButton: UIButton {
@IBInspectable var cornerRadius: CGFloat = 8
@IBInspectable var borderColor: UIColor? = .lightGray
override func draw(_ rect: CGRect) {
layer.cornerRadius = cornerRadius
layer.masksToBounds = true
layer.borderWidth = 1
layer.borderColor = borderColor?.cgColor
}
}