我有一个textView
当我点击textview的特定区域时,我找到了行号,但无法获取该行的文本
我需要获取特定行的文本并仅在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)
}
}
}
最佳答案
使用此扩展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
关于ios - 当我在特定位置点击UITextView时,我想更改该特定行的颜色,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48184845/