在iOS開發(fā)中咽白,經(jīng)常需要對一段文本的特殊文字顯示不同的顏色啤握,比如在發(fā)朋友圈時@某人時要把這個人高亮,同時點擊刪除按鈕這個人的名字要一起刪除而不是一個字一個字刪晶框,筆者公司目前開發(fā)的發(fā)表周報排抬,日報功能就遇到這方面的需求,現(xiàn)總結(jié)如下:
UITextView/UITextField/UILabel有一個屬性叫:attributedText授段,該屬性為NSAttributedString類型蹲蒲,該類的作用是可以為一段文本的不同rang的字體設(shè)置不同的大小,顏色侵贵,等届搁。可以利用該類實現(xiàn)富文本窍育,通常我們使用它的可變類型NSMutableAttributedString實現(xiàn)咖祭。
NSMutableAttributedString具有如下幾個方法:
//為某一范圍內(nèi)文字設(shè)置多個屬性
setAttributes: range:
//為某一范圍內(nèi)文字添加某個屬性
addAttribute: value: range:
//為某一范圍內(nèi)文字添加多個屬性
addAttributes: range:
//移除某范圍內(nèi)的某個屬性
removeAttribute: range:
NSMutableAttributedString的幾個常見屬性:
NSFontAttributeName
字體
NSParagraphStyleAttributeName
段落格式
NSForegroundColorAttributeName
字體顏色
NSBackgroundColorAttributeName
背景顏色
NSStrikethroughStyleAttributeName
刪除線格式
NSUnderlineStyleAttributeName
下劃線格式
NSStrokeColorAttributeName
刪除線顏色
NSStrokeWidthAttributeName
刪除線寬度
NSShadowAttributeName
陰影
下面進行簡單的應(yīng)用:
1.初始化一個UITextView。
let string = "今日主要工作:完成NSMutableAttributedString學(xué)習蔫骂,@點點"
//UITextView初始化
textView = UITextView()
textView?.delegate = self
textView?.alwaysBounceVertical = true
textView?.font = UIFont.systemFont(ofSize: 14)
textView?.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 200)
textView?.text = string
2.此時我們相對@點點幾個字進行高亮,模仿@mo某人效果牺汤,我們只需要找到@點點在文本中的rang辽旋,然后設(shè)置textView的attributedText屬性即可。
let mutableAtributSting = NSMutableAttributedString(string: string)
//找到@點點rang
let rang = (string as NSString).range(of: "@點點")
//顏色
mutableAtributSting.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 4/255.0, green: 186/255.0, blue: 215/255.0, alpha: 1.0), range:rang)
//字體大小
mutableAtributSting.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 18), range: rang)
textView?.attributedText = mutableAtributSting
以上就完成了對@點點幾個字的高亮檐迟,效果如下圖所示:
3.現(xiàn)在如果光標聚焦在點點后面(或者在兩個點字之間)點擊刪除按鈕补胚,需要將@點點這三個字一起刪除。首先我們得知道什么時候點擊了刪除按鈕追迟,可以在textView的代理方法中做文章溶其,當text為空時表示點擊了刪除按鈕,此時我們判斷光標的位置是否在@點點的rang范圍內(nèi)即可敦间。
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
}
代碼如下
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if !text.isEmpty {//不是刪除操作
return true
}
// 計算當前光標相對于文本開始位置的偏移量
let cursorOffset = textView.offset(from: textView.beginningOfDocument, to: (textView.selectedTextRange?.start)!)
let rang = (textView.text as NSString).range(of: "@點點")
if rang.location <= cursorOffset && rang.length + rang.location >= cursorOffset {//找到了
textView.text = (textView.text as NSString).replacingCharacters(in: rang, with: " ")
let cursorRange = NSRange(location:rang.location, length: 0)
textView.selectedRange = cursorRange
return false
}
return true
}
以上就是NSMutableAttributedString的基本使用及對于UITextView如何將某幾個字作為一個整體刪除瓶逃。