'Title not showing for custom UIButton class
I have created a custom UIButton class which features a round frame. The problem is although I set up the title property of each button from the storyboard they are not showing. I end up with round buttons with no titles showing inside them. I am trying to do a keypad like the one in default iOS passcode screen. My main view background color is not white and I am not using any background images for the buttons. Here is my code for the custom UIButton class.
import Foundation
import UIKit
class MyOwnButton: UIButton {
override init(frame: CGRect){
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
self.clipsToBounds = true
self.titleLabel?.font = UIFont.systemFontOfSize(33.0)
self.titleLabel?.textColor = UIColor.whiteColor()
self.layer.cornerRadius = self.frame.size.width / 2.0
self.layer.borderColor = UIColor.whiteColor().CGColor
self.layer.borderWidth = 2.0
}
}
Solution 1:[1]
Had same issue, this answer worked for me: Custom UIButton subclass not displaying title
Add super.layoutSubviews() after you override the function.
Solution 2:[2]
Have you set your UIButton's class as your custom class in storyboard??
Solution 3:[3]
Try to put all the things in init method and check.
import Foundation
import UIKit
class MyOwnButton: UIButton {
override init(frame: CGRect){
super.init(frame: frame)
self.clipsToBounds = true
self.titleLabel?.font = UIFont.systemFontOfSize(33.0)
self.titleLabel?.textColor = UIColor.whiteColor()
self.layer.cornerRadius = self.frame.size.width / 2.0
self.layer.borderColor = UIColor.whiteColor().CGColor
self.layer.borderWidth = 2.0
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
Solution 4:[4]
Here is working code for Swift 4
import UIKit
class MyOwnButton: UIButton {
override init(frame: CGRect){
super.init(frame: frame)
commonSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonSetup()
}
private func commonSetup() {
self.clipsToBounds = true
self.titleLabel?.font = UIFont.systemFont(ofSize: 33.0)
self.titleLabel?.textColor = UIColor.white
self.layer.cornerRadius = self.frame.size.width / 2.0
self.layer.borderColor = UIColor.white.cgColor
self.layer.borderWidth = 2.0
}
}
Solution 5:[5]
After setting the title of the button, simply:
[button sizeToFit];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Philipp Maurer |
| Solution 2 | Vishal Sonawane |
| Solution 3 | Bhadresh Mulsaniya |
| Solution 4 | iAmrSalman |
| Solution 5 | James Bush |
