Swift UILable UIButton 不同文字显示不同颜色,不同font

思路: 将不同的文字,设置为不同的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 不同文字显示不同颜色,不同font)