Skip to content

Instantly share code, notes, and snippets.

@bgayman
Last active January 27, 2018 15:12
Show Gist options
  • Save bgayman/1cd0ade8d14b074f220a6242a088271e to your computer and use it in GitHub Desktop.
Save bgayman/1cd0ade8d14b074f220a6242a088271e to your computer and use it in GitHub Desktop.
import UIKit
import PlaygroundSupport
class ViewController: UIViewController {
var notesTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
notesTextView = UITextView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
view.addSubview(notesTextView)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
notesTextView.addGestureRecognizer(tapGesture)
notesTextView.text = """
WHEN, IN 1993, Hamid Biglari left his job as a theoretical nuclear physicist at Princeton to join McKinsey consulting, what struck him was that “companies were displacing nations as the units of international competition.”
This seemed to him a pivotal change. International corporations have a different lens. They optimize globally, rather than nationally. Their aim is to maximize profits across the world — allocating cash where it is most beneficial, finding labor where it is cheapest — not to pursue some national interest.
The shift was fast-forwarded by advances in communications that rendered distance irrelevant, and by the willingness in most emerging markets to open borders to foreign investment and new technologies.
Hundreds of millions of people in these developing countries were lifted from poverty into the middle class. Conversely, in Western societies, a hollowing out of the middle class began as manufacturing migrated, technological advances eliminated jobs and wages stagnated.
Looking back, it’s now easy enough to see that the high point of democracy — the victory of open systems over the Soviet imperium that brought down the Berlin Wall in 1989 and set free more than 100 million Central Europeans — was quickly followed by the unleashing of economic forces that would undermine democracies. Far from ending history, liberalism triumphant engendered a reaction.
"""
}
@objc func handleTap(_ sender: UITapGestureRecognizer) {
guard let textView = sender.view as? UITextView else { return }
var pointOfTap = sender.location(in: textView)
print("x:\(pointOfTap.x) , y:\(pointOfTap.y)")
let word = self.word(atPosition: pointOfTap)
print(word ?? "NO WORD")
}
func word(atPosition: CGPoint) -> String? {
guard let tapPosition = notesTextView.closestPosition(to: atPosition),
let textRange = notesTextView.tokenizer.rangeEnclosingPosition(tapPosition , with: .word, inDirection: 1) else { return nil }
let tappedWord = notesTextView.text(in: textRange)
return tappedWord
}
}
PlaygroundPage.current.liveView = ViewController()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment