*The next code works in Swift 3 and above.
You can not set the buttonType of a UIButton subclass by design. It’s routinely set to customized which suggests you get a plain look and habits as a place to begin.
If you wish to reuse code that units the button’s look, you are able to do this with out subclassing. One strategy is by offering manufacturing unit strategies that create a UIButton and set visible properties.
Instance manufacturing unit methodology to keep away from subclassing
extension UIButton {
static func createStandardButton() -> UIButton {
let button = UIButton(sort: UIButtonType.system)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
button.setTitleColor(UIColor.black, for: .regular)
button.setTitleColor(UIColor.grey, for: .highlighted)
return button
}
}
let button = UIButton.createStandardButton()
I keep away from subclassing UIButton when different customization methods suffice. The manufacturing unit methodology instance is one possibility. There are different choices together with the UIAppearance API, and many others.
Typically there are customization wants that require subclassing. For instance, I’ve created UIButton subclasses to take tremendous management over how the button animates in response to the touch occasions or to have the button name a predefined delegate or closure when tapped (versus assigning a #selector to every occasion).
The next is a primary UIButton subclass instance as a place to begin.
Instance UIButton Subclass
inside class CustomButton: UIButton {
init() {
// The body could be set exterior of the initializer. Default to zero.
tremendous.init(body: CGRect.zero)
initialize()
}
required init?(coder aDecoder: NSCoder) {
// Known as when instantiating from storyboard or nib
tremendous.init(coder: aDecoder)
initialize()
}
func initialize() {
print(“Execute widespread initialization code”)
}
}
let button = CustomButton()
print(button.buttonType == .customized) // true
Â
A observe about UIButtonType
Because the query was requested in 2012, UIButtonType.roundedRect has been deprecated. The header file feedback say to make use of UIButtonType.system as a substitute.
The next is from UIButton.h transformed to Swift in Xcode
public enum UIButtonType : Int {
case customized // no button sort
@accessible(iOS 7.0, *)
case system // customary system button
case detailDisclosure
case infoLight
case infoDark
case contactAdd
public static var roundedRect: UIButtonType { get } // Deprecated, use UIButtonTypeSystem as a substitute
}
And this is the essential information for setting the so-called “Fashion” setting seen in a storyboard drop-down menu:
https://stackoverflow.com/a/72913854/294884