Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active August 21, 2019 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KentarouKanno/a6ab9b1561fa46cf0c71711b1aec6ff6 to your computer and use it in GitHub Desktop.
Save KentarouKanno/a6ab9b1561fa46cf0c71711b1aec6ff6 to your computer and use it in GitHub Desktop.
  • 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
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment