Swift富文本

字符串中单个变色

extension String {
 public func getAttributedString(sender:String) -> NSMutableAttributedString {
        
        let attributedString = NSMutableAttributedString.init()
        
        let jndex   = self.range(of: sender)
        let before = self.substring(to: (jndex?.lowerBound)!)
        
        let beforeAttributedString = NSAttributedString.init(string: before, attributes: [NSFontAttributeName:UIFont.boldSystemFont(ofSize: 16),NSForegroundColorAttributeName:UIColor.black])
        attributedString.append(beforeAttributedString)
        
        let titleAttributedString = NSAttributedString.init(string: sender, attributes: [NSForegroundColorAttributeName:UIColor.cyan,NSFontAttributeName:UIFont.boldSystemFont(ofSize: 16)])
        attributedString.append(titleAttributedString)
        
        let upper = self.substring(from: (jndex?.upperBound)!)
        
        let contentAttributedString = NSAttributedString.init(string: upper, attributes: [NSFontAttributeName:UIFont.boldSystemFont(ofSize: 16),NSForegroundColorAttributeName:UIColor.black])
        
        attributedString.append(contentAttributedString)
        return attributedString
    }
}

你可能感兴趣的:(Swift富文本)