Created
May 18, 2019 02:20
-
-
Save celikomer/6bcf63b5887d65fec8d2598646aeeb58 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
let string = "Lorem ipsum dolor sit amet\n #test# #ganothertest# not a tag" | |
let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 200, height: 100)) | |
textView.text = string | |
textView.font = UIFont(name: "Helvetica", size: 15) | |
func frameOfTextInRange(range:NSRange, inTextView textView:UITextView) -> CGRect { | |
let beginning = textView.beginningOfDocument | |
let start = textView.position(from: beginning, offset: range.location) | |
let end = textView.position(from: start!, offset: range.length) | |
let textRange = textView.textRange(from: start!, to: end!) | |
let rect = textView.firstRect(for: textRange!) | |
return textView.convert(rect, from: textView) | |
} | |
//let textViewBG = UIView(frame: textView.bounds) | |
//textView.backgroundColor = UIColor.clear | |
//textViewBG.backgroundColor = UIColor.white | |
let pattern = "(\\#[a-zA-Z]+\\b\\#)(?!;)" | |
let regex = try! NSRegularExpression(pattern: pattern, options: []) | |
let matches = regex.matches(in: string, options: [], range: NSMakeRange(0, string.count)) | |
let attributedString = NSMutableAttributedString(string: string) | |
let myAttr = [NSAttributedString.Key.foregroundColor: UIColor.white] | |
let myString = textView.attributedText.mutableCopy() as! NSMutableAttributedString | |
let paragraphStyle = NSMutableParagraphStyle() | |
paragraphStyle.lineHeightMultiple = 1.3 | |
let textAttributes = [NSMutableAttributedString.Key.paragraphStyle: paragraphStyle, | |
NSAttributedString.Key.font: UIFont(name: "Helvetica", size: 15)] | |
myString.addAttributes(textAttributes as [NSAttributedString.Key : Any], range: NSMakeRange(0, textView.text.count)) | |
textView.attributedText = myString.copy() as? NSAttributedString | |
for m in matches { | |
// myString.addAttributes(myAttr, range: m.range) | |
myString.addAttributes(myAttr, range: m.range) | |
let range = m.range | |
var frame = frameOfTextInRange(range: range, inTextView: textView) | |
frame = frame.insetBy(dx: -1.6, dy: 2) | |
frame = frame.offsetBy(dx: 0, dy: 2) | |
let v = UIView(frame: frame) | |
v.layer.cornerRadius = v.frame.height / 2 | |
v.backgroundColor = #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1) | |
textView.insertSubview(v, at: 0) | |
} | |
textView.attributedText = myString.copy() as? NSAttributedString | |
//textViewBG.addSubview(textView) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment