swift-富文本属性设置的封装

最近在做一个练习项目的时候,经常写到要设置富文本属性的地方,所以写了一个简单的封装,因为swift的字符下标采用的是string.index的类型,而富文本熟悉设置是原有的Range(Int, Int)类型。所以在将字符的string.index转为Int这方面耗费了不少功夫,最终也还是没有找到直接转换的方法。而是通过截取string.index的内容来获取相对应的Int下标。虽然是挺非主流的方法,但是本人亲测有效。另外如果你有更好的string.index转Int下标的方法,欢迎分享,当然是在swift3.0的环境下,哈哈。

  • 结果


    swift-富文本属性设置的封装_第1张图片
    屏幕快照 2017-03-23 下午1.50.01.png
  • 调用示例
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let lbl = UILabel.init(with: "", textColor: UIColor.black, fontSize: 15)
        let originString = "周末闲着无聊,想起最近遇到一个关于文字显示设置的小问题,想着以后可能还会经常用到,所以趁这个时候一起整理一下,方便以后备用"
        //初始化一个CHAttributeStringTool对象
        let ch = CHAttributeStringTool.init(withString: originString)
        //设置富文本属性,注:属性可以叠加,from:起始字符,传""表示从第一个字符;to:截止字符,传""表示到最后一个字符
        ch.set(strikeLineColor: UIColor.red, lineSize: 5, from: "想着以后", to: "用到")
        //赋值富文本属性
        lbl.attributedText = ch.chString
        lbl.frame = CGRect(x: (UIScreen.main.bounds.size.width - 200)/2, y: 100, width: 200, height: 300)
        lbl.numberOfLines = 0
        self.view.addSubview(lbl)
        
    }
}
//MARK: - UIlabel
extension UILabel {
    convenience init(with text: String, textColor: UIColor,fontSize: CGFloat) {
        self.init()
        self.text = text
        self.font = UIFont.systemFont(ofSize: fontSize)
        self.textColor = textColor
    }
}
  • 以下是封装代码,有用的话直接拷走就行啦,然后记得给个赞哈哈哈
import UIKit
class CHAttributeStringTool: NSObject {
    //MARK: - 内部属性
    private var originString: String?
    private var characterCount: Int = 0
    private var style = NSMutableParagraphStyle()
    private var range: NSRange?
    //MARK: - 外部属性
    public var chString: NSMutableAttributedString?
    
    //MARK: - 外部方法
    init(withString str: String) {
        originString = str
        characterCount = str.characters.count
        chString = NSMutableAttributedString.init(string: str)
    }
    ///设置删除线
    public func set(strikeLineColor lineColor: UIColor,lineSize: Float, from: String, to: String) {
        let range = calculRange(withString: originString!, from: from, to: to)
        chString?.addAttributes([NSStrikethroughStyleAttributeName: lineSize], range: range)
        chString?.addAttributes([NSStrikethroughColorAttributeName: lineColor], range: range)
    }
    ///设置下划线
    public func set(underLineColor lineColor: UIColor, lineSize: Float, from: String, to: String) {
        let range = calculRange(withString: originString!, from: from, to: to)
        chString?.addAttributes([NSUnderlineStyleAttributeName: lineSize], range: range)
        chString?.addAttributes([NSUnderlineColorAttributeName: lineColor], range: range)
    }
    ///设置字体倾斜
    public func set(Obliqueness size: CGFloat, from: String, to: String) {
        let range = calculRange(withString: originString!, from: from, to: to)
        chString?.addAttributes([NSObliquenessAttributeName: size], range: range)
    }
    ///设置字距
    public func set(stringSpacing: Float, from: String, to: String) {
        let range = calculRange(withString: originString!, from: from, to: to)
        chString?.addAttributes([NSKernAttributeName: stringSpacing], range: range)
    }
    ///设置字号
    public func set(fontSize: CGFloat, from: String, to: String) {
        let range = calculRange(withString: originString!, from: from, to: to)
        chString?.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: fontSize)], range: range)
    }
    ///设置粗体字号
    public func set(boldFontSize: CGFloat, from: String, to: String) {
        let range = calculRange(withString: originString!, from: from, to: to)
        chString?.addAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: boldFontSize)], range: range)
    }
    ///设置前景色
    public func set(foregroundColor color: UIColor, from: String, to: String) {
        let range = calculRange(withString: originString!, from: from, to: to)
        chString?.addAttributes([NSForegroundColorAttributeName: color], range: range)
    }
    ///设置背景色
    public func set(backgroundColor color: UIColor, from: String, to: String) {
        let range = calculRange(withString: originString!, from: from, to: to)
        chString?.addAttributes([NSBackgroundColorAttributeName: color], range: range)
    }
    
    ///段落属性相关
    ///设置行间距
    public func set(lineSpacing: CGFloat) {
        let range = calculRange(withString: originString!, from: "", to: "")
        style.lineSpacing = lineSpacing
        chString?.addAttributes([NSParagraphStyleAttributeName: style], range: range)
    }
    ///设置首行缩进距离
    public func set(firstLineIndent indent : CGFloat) {
        let range = calculRange(withString: originString!, from: "", to: "")
        style.firstLineHeadIndent = indent
        chString?.addAttributes([NSParagraphStyleAttributeName: style], range: range)
    }
    ///设置每行行首缩进距离
    public func set(headerIndent indent: CGFloat) {
        let range = calculRange(withString: originString!, from: "", to: "")
        style.headIndent = indent
        chString?.addAttributes([NSParagraphStyleAttributeName: style], range: range)
    }
    ///设置每行行末缩进距离
    public func set(tailIndent indent: CGFloat) {
        let range = calculRange(withString: originString!, from: "", to: "")
        style.tailIndent = -indent
        chString?.addAttributes([NSParagraphStyleAttributeName: style], range: range)
    }
    ///设置文本对齐
    public func set(textAlignment alignment: NSTextAlignment) {
        let range = calculRange(withString: originString!, from: "", to: "")
        style.alignment = alignment
        chString?.addAttributes([NSParagraphStyleAttributeName: style], range: range)
    }
    
    //MARK: - 内部方法
    ///计算range
    private func calculRange(withString originStr:String, from: String, to: String)-> NSRange {
        var loc1 = 0
        var loc2 = 0
        loc1 = from == "" ? 0 : stringIndexToInt(withString: originStr, calculString: from).start
        loc2 = to == "" ? characterCount : stringIndexToInt(withString: originStr, calculString: to).end
        return NSMakeRange(loc1, loc2 - loc1)
    }
    
    ///string.index转Int
    private func stringIndexToInt(withString originString: String, calculString: String)-> (start: Int, end: Int) {
        let range = originString.range(of: calculString)
        if range == nil {
            print("originString中不包含calculString")
            return (0,0)
        }
        let rangeStr = String(describing: range?.lowerBound)
        print(rangeStr.characters)
        
        let positionRange1 = rangeStr.range(of: "_position: ")
        let positionRange2 = rangeStr.range(of: ")")
        print(rangeStr)
        let str = rangeStr.substring(with: ((positionRange1?.upperBound)!..<(positionRange2?.lowerBound)!))
        
        let rangeStr2 = String.init(describing: range?.upperBound)
        print(rangeStr2)
        let positionRange3 = rangeStr2.range(of: "_position: ")
        let positionRange4 = rangeStr2.range(of: ")")
        let str2 = rangeStr2.substring(with: ((positionRange3?.upperBound)!..<(positionRange4?.lowerBound)!))
        print(str2)
        let result = (start: Int(str)!, end: Int(str2)!)
        return result
    }
}

你可能感兴趣的:(swift-富文本属性设置的封装)