- UIButtonにアンダースコア付きの文字を設定して押下時リンクタップの様に見える。
※numberOfLinesを0にして複数行の時にも改行されるようになってます。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var button: CustomButton!
let underLineString = "Patient Name "
let text = "click for patient info"
override func viewDidLoad() {
super.viewDidLoad()
button.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
button.titleLabel?.numberOfLines = 0
let normalAttributes: [NSAttributedString.Key : Any] = [.underlineStyle: NSUnderlineStyle.single.rawValue,
.foregroundColor : UIColor.blue]
let highlightedAttributes: [NSAttributedString.Key : Any] = [.underlineStyle: NSUnderlineStyle.single.rawValue,
.foregroundColor : UIColor.red]
let normalAttributedString = NSMutableAttributedString()
normalAttributedString.append(NSAttributedString(string: underLineString, attributes: normalAttributes))
normalAttributedString.append(NSAttributedString(string: text, attributes: nil))
button.setAttributedTitle(normalAttributedString, for: .normal)
let highlightedAttributedString = NSMutableAttributedString()
highlightedAttributedString.append(NSAttributedString(string: underLineString, attributes: highlightedAttributes))
highlightedAttributedString.append(NSAttributedString(string: text, attributes: nil))
button.setAttributedTitle(highlightedAttributedString, for: .highlighted)
}
@IBAction func tappedButton(_ sender: UIButton) {
print("Tapped!")
}
}
class CustomButton: UIButton {
override var intrinsicContentSize: CGSize {
return titleLabel!.bounds.size
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel!.preferredMaxLayoutWidth = titleLabel!.frame.size.width
imageView?.bounds = titleLabel!.bounds
}
}