Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Coder-ACJHP/8b0cc90a39378e72dfec5942130078d7 to your computer and use it in GitHub Desktop.
Save Coder-ACJHP/8b0cc90a39378e72dfec5942130078d7 to your computer and use it in GitHub Desktop.
TextView that allows to tap on attributed strings, it returns location of tapped word as CGPoint and shows popupView.
//
// MultipleTapableAttributedStringTextView.swift
// TapOnAttributedText
//
// Created by Onur Işık on 18.09.2019.
// Copyright © 2019 Onur Işık. All rights reserved.
//
import UIKit
class MultipleTapableAttributedStringTextView: UIViewController {
private let popupView: UIView = {
let v = UIView(frame: CGRect(origin: .zero, size: .init(width: 100, height: 100)))
v.backgroundColor = .green
v.alpha = 0
return v
}()
private let textView: UITextView = {
let textView = UITextView(frame: .zero)
textView.backgroundColor = .white
textView.isEditable = false
textView.isSelectable = false
textView.spellCheckingType = .no
textView.translatesAutoresizingMaskIntoConstraints = false
return textView
}()
private let specialWords: [String] = [
"Aenean", "Curabitur", "adipiscing", "laoreet", "sapien"
]
private var colorCounter: Int = 0
private let specialWordsColors: [UIColor] = [
.red, .brown, .purple, .orange, .yellow
]
private var tapGesture: UITapGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
self.view.addSubview(textView)
NSLayoutConstraint.activate([
textView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
textView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
textView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
textView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor)
])
textView.text = """
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. vulputate eleifend tellus leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,
"""
makeSpecialWordsUnderlinedWithRandomColor(wordList: specialWords)
tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
textView.addGestureRecognizer(tapGesture)
view.addSubview(popupView)
}
private func makeSpecialWordsUnderlinedWithRandomColor(wordList: [String]) {
let attributedString = NSMutableAttributedString(string: textView.text)
let totalRange = NSRange(location: 0, length: textView.text.count)
let attributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.foregroundColor: UIColor.black,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20),
]
attributedString.addAttributes(attributes, range: totalRange)
for word in wordList {
if let regularExpression = try? NSRegularExpression(pattern: "\(word)", options: .caseInsensitive) {
let matchedResults = regularExpression.matches(in: textView.text!,
options: [],
range: NSRange(location: 0, length: attributedString.length))
for matched in matchedResults {
if colorCounter > specialWordsColors.count - 1 {
colorCounter = 0
}
attributedString.addAttribute(NSAttributedString.Key.underlineStyle,
value: NSUnderlineStyle.thick.rawValue,
range: matched.range)
attributedString.addAttribute(NSAttributedString.Key.underlineColor,
value: specialWordsColors[colorCounter],
range: matched.range)
colorCounter += 1
}
textView.attributedText = attributedString
}
}
}
@objc private func handleTap(_ gesture: UITapGestureRecognizer) {
guard let text = textView.attributedText?.string else { return }
for word in specialWords {
guard let searchingTextRange = text.range(of: word) else { break }
let nsRange = NSRange(searchingTextRange, in: text)
let result: (Bool, CGPoint?) = gesture.didTapAttributedTextInTextView(textView: textView, inRange: nsRange)
if result.0 {
self.popupView.frame.origin.x = result.1!.x - (popupView.frame.width / 2)
self.popupView.frame.origin.y = result.1!.y + (popupView.frame.height / 2)
self.popupView.alpha = 1.0
}
}
}
}
extension UITapGestureRecognizer {
func didTapAttributedTextInTextView(textView: UITextView, inRange targetRange: NSRange) -> (Bool, CGPoint?) {
let layoutManager = textView.layoutManager
var location = self.location(in: textView)
location.x -= textView.textContainerInset.left
location.y -= textView.textContainerInset.top
let characterIndex = layoutManager.characterIndex(for: location,
in: textView.textContainer,
fractionOfDistanceBetweenInsertionPoints: nil)
if characterIndex < textView.textStorage.length {
return (NSLocationInRange(characterIndex, targetRange), location)
}
return (false, nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment