I know that this problem has been solved in Objective-C, but I haven't seen any solution to it in Swift. I have tried to convert the solution code from this post, but I'm getting errors:
func textTapped(recognizer: UITapGestureRecognizer){
var textView: UITextView = recognizer.view as UITextView
var layoutManager: NSLayoutManager = textView.layoutManager
var location: CGPoint = recognizer.locationInView(textView)
location.x -= textView.textContainerInset.left
location.y -= textView.textContainerInset.top
var charIndex: Int
charIndex = layoutManager.characterIndexForPoint(location, inTextContainer: textView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
if charIndex < textView.textStorage.length {
// do the stuff
println(charIndex)
}
}
I think the problem is in this line (see error here):
var textView: UITextView = recognizer.view as UITextView
... which I have converted from Objective-C based on this line:
UITextView *textView = (UITextView *)recognizer.view;
Finally, I am also in doubt about how this function should be called. As I understand it, the function should be passed to a Selector in viewDidLoad(), like this:
let aSelector: Selector = "textTapped:"
let tapGesture = UITapGestureRecognizer(target: self, action: aSelector)
tapGesture.numberOfTapsRequired = 1
view.addGestureRecognizer(tapGesture)
Because I'm getting the before mentioned error, I'm not sure if it would work. But I'm thinking that I would need to pass the parameter in the textTapped function (recognizer) into the Selector as well. However, I've read that you can only pass the function and not any parameters.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…