[英]When I tap on UITextView at a particular place I want to change the color of that particular line
我有一個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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.