YYLabel的富文本设置

实现以上红框内的效果,设置部分字体内容的颜色为红色,前面按钮可以点击,红色字体内容也可以点击:

1、导入YYText:

import YYText

2、定义YYLabel属性

var protocolLabel = YYLabel()

3、代码实现

func initUI() {

self.protocolLabel.font = UIFont.systemFont(ofSize: 12.0)

        self.protocolLabel.textColor = UIColor.init(rgb: 0x161616)

        self.protocolLabel.textAlignment = .center

        self.protocolLabel.isUserInteractionEnabled = true

        view.addSubview(self.protocolLabel)

        self.protocolLabel.snp.makeConstraints { (make) in

            make.top.equalTo(vercodeUnderLineView.snp.bottom).offset(15.cgFloat.pad(20).adaptHeight())

            make.left.equalTo(vercodeUnderLineView)

            make.right.equalToSuperview().offset(-45.cgFloat.pad(-211).adaptWidth())

        }

        self.protocolLabel.numberOfLines = 2


        //设置协议

        setAttribute(markup: "《AI美照馆用户协议及隐私政策》")

}



    //MARK:设置协议

    func setAttribute(markup:String) {

        let iconImg =UIButton()

        iconImg.setImage(UIImage(named:"ic_radio button_nor"), for: .normal)

        iconImg.setImage(UIImage(named:"ic_radio button_nsel"), for: .selected)

        iconImg.hitEdgeInsets=UIEdgeInsets(top:20, left:20, bottom:20, right:20)


        //MARK:设置按钮点击事件

        iconImg.rx.tap.subscribe(onNext: {_in

            iconImg.isSelected=!iconImg.isSelected

        }).disposed(by: disposeBag)

        iconImg.frame=CGRect(x:0, y:0, width:15, height:15)

        letatt =YYTextAttachment(content: iconImg)

        att.contentMode= .left

        lettext =String(format:" 点击登录即代表同意%@",markup)

        let attributeStr =NSMutableAttributedString.yy_attachmentString(withContent: iconImg, contentMode: .left, attachmentSize:CGSize(width:15, height:15), alignTo:UIFont.systemFont(ofSize:12), alignment: .center)

        attributeStr.yy_insertString(text, at:1)

        //MARK:设置协议点击事件

        attributeStr.yy_setTextHighlight(NSRange(location:11, length: markup.count), color:UIColor.init(rgb:0xF76F00), backgroundColor:nil) { (view, att, range, rect)in

            print("跳转协议")

        }


        self.protocolLabel.attributedText = attributeStr

    }

你可能感兴趣的:(YYLabel的富文本设置)