使用相交作为发件人

时间:2018-08-18 21:31:12

标签: ios swift attributes intersect

在滚动时,我尝试检查potatoText中某个字符的属性,一旦该字符触及胡萝卜行。下面,我有代码检查属性,如果您触摸potatoText中的字符。希望将其变形以检查相交值。

@IBOutlet weak var carrotLine: UILabel!
@IBOutlet weak var potatoText: UITextView!

....

let tap = UITapGestureRecognizer(target: self, action: #selector(myMethodToHandleTap(_:)))
    tap.delegate = self
    potatoText.addGestureRecognizer(tap)
}
@objc func myMethodToHandleTap(_ sender: UITapGestureRecognizer) {

    let myTextView = sender.view as! UITextView
    let layoutManager = myTextView.layoutManager

    // location of tap in myTextView coordinates and taking the inset into account
    var location = sender.location(in: myTextView)
    location.x -= myTextView.textContainerInset.left;
    location.y -= myTextView.textContainerInset.top;

    // character index at tap location
    let characterIndex = layoutManager.characterIndex(for: location, in: myTextView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)

    // if index is valid then do something.
    if characterIndex < myTextView.textStorage.length {

        // print the character index
        print("character index: \(characterIndex)")

        // print the character at the index
        let myRange = NSRange(location: characterIndex, length: 1)
        let substring = (myTextView.attributedText.string as NSString).substring(with: myRange)
        print("character at index: \(substring)")

        // check if the tap location has a certain attribute
        let attributeName = "MyCustomAttributeName"
        let attributeValue = myTextView.textStorage.attribute(.foregroundColor, at: characterIndex, effectiveRange: nil) as? UIColor
        print("You tapped on \(attributeName) and the value is: \(String(describing: attributeValue))")
    }
}

0 个答案:

没有答案