美文网首页Swift 探索与思考
Swift UILable UIButton 不同文字显示不同颜

Swift UILable UIButton 不同文字显示不同颜

作者: steveMoriya | 来源:发表于2018-08-22 10:52 被阅读98次

    思路: 将不同的文字,设置为不同的NSAttributedString (其中包含颜色,font等属性)

    let kindLb = UILabel(frame:CGRect(x: screenWidth/2 - 100, y:  remainNumTitleLb.frame.maxY + 10, width: 100 , height: 17))
    
    let string = "steve_Moriya"
    let aa = (string as NSString).range(of: "_")
    let bb = (string as NSString).substring(to: aa.location)
    let cc = (string as NSString).substring(from: aa.location + 1)
            
    let kindLbStr1 = NSAttributedString(string: bb, attributes: [NSAttributedStringKey.foregroundColor : UIColor.white, NSAttributedStringKey.font : UIFont.systemFont(ofSize: 20)])
    let kindLbStr2 = NSAttributedString(string: cc, attributes: [NSAttributedStringKey.foregroundColor : ThemePurpleColor, NSAttributedStringKey.font : UIFont.systemFont(ofSize: 10)])
    
    let kindLbStr = NSMutableAttributedString()
    kindLbStr.append(kindLbStr1)
    kindLbStr.append(kindLbStr2)
    
    //UILabel和UIButton直接使用 KindLbStr 
    
    kindLb.attributedText = kindLbStr
    
    

    UIButton的设置方法有一点不同

    
    let rigistButton = UIButton.init(type: UIButtonType.custom)
    rigistButton.frame = CGRect(x: 40, y:  loginButton.frame.maxY + 20, width: 160, height: 20)
    
    rigistButton.setAttributedTitle(kindLbStr, for: UIControlState.normal)
    
    

    相关文章

      网友评论

        本文标题:Swift UILable UIButton 不同文字显示不同颜

        本文链接:https://www.haomeiwen.com/subject/vtueiftx.html