365bet体育|www.635288com-365体育手机在线

热门关键词: 365bet体育,www.635288com,365体育手机在线

方便使用...

2020-05-06 作者:365bet体育   |   浏览(123)
有时候想对字符串进行某些特殊操作,需要获取NSRange,比如富文本...
下面简单在String上进行扩展,方便使用...
extension String { /// 字符串的匹配范围 方法一 /// /// - Parameters: /// - matchStr: 要匹配的字符串 /// - Returns: 返回所有字符串范围 func exMatchStrRange(matchStr: String) -> [NSRange] { var allLocation = [Int]() //所有起点 let matchStrLength = (matchStr as NSString).length //currStr.characters.count 不能正确统计表情 let arrayStr = self.componentsSeparatedByString var currLoc = 0 arrayStr.forEach { currStr in currLoc  = (currStr as NSString).length allLocation.append currLoc  = matchStrLength } allLocation.removeLast() return allLocation.map { NSRange(location: $0, length: matchStrLength) } //可把这段放在循环体里面,同步处理,减少再次遍历的耗时 } /// 字符串的匹配范围 方法二 /// /// - Parameters: /// - matchStr: 要匹配的字符串 /// - Returns: 返回所有字符串范围 func exMatchStrNSRange(matchStr: String) -> [NSRange] { var selfStr = self as NSString var withStr = Array(count: (matchStr as NSString).length, repeatedValue: "X").joinWithSeparator //辅助字符串 if matchStr == withStr { withStr = withStr.lowercaseString } //临时处理辅助字符串差错 var allRange = [NSRange]() while selfStr.rangeOfString.location != NSNotFound { let range = selfStr.rangeOfString allRange.append(NSRange(location: range.location,length: range.length)) selfStr = selfStr.stringByReplacingCharactersInRange(NSMakeRange(range.location, range.length), withString: withStr) } return allRange }}

let str = "吾生也有涯而知也无涯,以有涯随无涯殆己"let allRange1 = str.exMatchStrRangelet allRange2 = str.exMatchStrNSRangeprint(allRange1) // [, ]print(allRange2) // [, , , ]

图片 1

import UIKitclass ViewController: UIViewController { @IBOutlet weak var label: UILabel! override func viewDidLoad() { super.viewDidLoad() let str = "吾生也有涯,而知也无涯。n以有涯随无涯,殆已!n已而为知者,殆而已矣!" let attributeString = NSMutableAttributedString(string: str) let allRange1 = str.exMatchStrRange let allRange2 = str.exMatchStrRange let allRange3 = str.exMatchStrRange allRange1.forEach { attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.orangeColor(), range: $0) attributeString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue-Bold", size: 16)!,range: $0) } allRange2.forEach { attributeString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue-Bold", size: 18)!,range: $0) } allRange3.forEach { attributeString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.redColor(), range: $0) } label.attributedText = attributeString }}

本文由365bet体育发布于365bet体育,转载请注明出处:方便使用...

关键词: 字符串 Swift NSRange