这是我对 UIButton 的方便初始化:
convenience init(underlinedTitle: String, font: UIFont, color: UIColor) {
var configuration = UIButton.Configuration.plain()
configuration.title = underlinedTitle
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var outgoing = incoming
outgoing.font = font
outgoing.foregroundColor = color
outgoing.underlineStyle = .single
outgoing.underlineColor = color
return outgoing
}
self.init(configuration: configuration)
}
效果如下:
为什么没有下划线?
尝试使用此答案中的方法 https://stackoverflow.com/a/41166179/11335258
@IBOutlet weak var yourButton: UIButton!
var attrs = [
NSFontAttributeName : UIFont.systemFontOfSize(19.0),
NSForegroundColorAttributeName : UIColor.redColor(),
NSUnderlineStyleAttributeName : 1]
var attributedString = NSMutableAttributedString(string:"")
override func viewDidLoad() {
super.viewDidLoad()
let buttonTitleStr = NSMutableAttributedString(string:"My Button", attributes:attrs)
attributedString.appendAttributedString(buttonTitleStr)
yourButton.setAttributedTitle(attributedString, forState: .Normal)
}