如何在Button中给title添加下划线

设计图如下:

Snip20180719_1.png

1.代码如下:

//登录方式的选择
    let selectedLoginBtn: UIButton = {
        let button = UIButton()
        button.titleLabel?.font = UIFont.systemFont(ofSize: 12.plan_scaleValue)
        let attributedStr: NSMutableAttributedString = NSMutableAttributedString.init(string: "账号密码登录")
        let titleRange: NSRange = NSRange.init(location: 0, length: attributedStr.length)
        let number: NSNumber = NSNumber(integerLiteral: NSUnderlineStyle.styleThick.rawValue)
        attributedStr.addAttributes([NSUnderlineStyleAttributeName: number,
                                     NSForegroundColorAttributeName: COLOR_222222,
                                     NSFontAttributeName: UIFont.systemFont(ofSize: 12.plan_scaleValue)],
                                     range: titleRange)
        button.setAttributedTitle(attributedStr, for: UIControlState.normal)
        button.addTarget(self, action: #selector(selectedLoginAction(_ :)), for: .touchUpInside)
        button.isUserInteractionEnabled = true
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

2.NSUnderlineStyle中的key值对应的解释说明

    case styleNone  //无下划线

    case styleSingle // 有下划线,样式为单细线

    @available(iOS 7.0, *)
    case styleThick  //有下划线,样式为单粗线

    @available(iOS 7.0, *)
    case styleDouble //有下划线,样式为双细线

    
    @available(iOS 7.0, *)
    public static var patternSolid: NSUnderlineStyle { get } //有下划线,样式为连续实现

    @available(iOS 7.0, *)
    case patternDot  //有下划线,样式为虚线   比如这样:------

    @available(iOS 7.0, *)
    case patternDash  //有下划线,样式为破折线   比如这样:—— —— ——

    @available(iOS 7.0, *)
    case patternDashDot   //有下划线,样式为连续的点和破折线   比如这样:——-——-——-

    @available(iOS 7.0, *)
    case patternDashDotDot   //有下划线,样式为连续的破折号、点、点   比如这样:——-——-——-

    
    @available(iOS 7.0, *)
    case byWord     //在有空格的地方不设置下划线/删除线
}

你可能感兴趣的:(如何在Button中给title添加下划线)