当我在特定的地方点击UITextView时,我想要更改该特定行的颜色

时间:2018-01-10 10:06:05

标签: ios swift uitextview

  1. 我有一个textView

  2. 当我点击textview的某个特定区域时,我会找到行号,但我无法获取该行的文字

  3. 我需要获取特定行的文本,并在textview中仅更改该文本的颜色

     func HandleTapped(sender: UITapGestureRecognizer)
     {
         print("tapped")
         if sender.state == .recognized {
             let location = sender.location(ofTouch: 0, in: TextView)
             print(location)
             if location.y >= 0 && location.y <= TextView.contentSize.height {
            guard let font = TextView.font else {
                return
             }
            let line = Int((location.y - TextView.textContainerInset.top) / font.lineHeight) + 1
            print("Line is \(line)")
            let text=TextView.textContainer
            print(text)
    
    
           }
       }
    }
    

1 个答案:

答案 0 :(得分:0)

将此扩展名用于UITextView以获取当前行所选的文本行:

func getLineString() -> String {
    return (self.text! as NSString).substringWithRange((self.text! as NSString).lineRangeForRange(self.selectedRange))
}

然后,您需要将所有文本更改为属性文本,并将所选行文本的范围更改为高亮颜色。类似的东西:

let allText = textView.text
let lineText = textView.getLineString()

let attrText = NSMutableAttributedString(string: allText)

let regularFont = UIFont(name: "Arial", size: 30.0)! // Make this whatever you need
let highlightFont = UIFont(name: "Arial-BoldMT", size: 30.0)! // Make this whatever you need

//  Convert allText to NSString because attrText.addAttribute takes an NSRange.
let allTextRange = (allText as NSString).rangeOfString(allText)
let lineTextRange = (allText as NSString).rangeOfString(lineText)

attrText.addAttribute(NSFontAttributeName, value: regularFont, range: allTextRange)
attrText.addAttribute(NSFontAttributeName, value: highlightFont, range: lineTextRange)

textView.attributedText = attrText