Character index at touch point for UILabel

后端 未结 7 1779
Happy的楠姐
Happy的楠姐 2020-12-05 03:09

For a UILabel, I\'d like to find out which character index is at specific point received from a touch event. I\'d like to solve this problem for iOS 7 using Tex

7条回答
  •  无人及你
    2020-12-05 03:36

    I have implemented the same on swift 3. Below is the complete code to find Character index at touch point for UILabel, it can help others who are working on swift and looking for the solution :

        //here myLabel is the object of UILabel
        //added this from @warly's answer
        //set font of attributedText
        let attributedText = NSMutableAttributedString(attributedString: myLabel!.attributedText!)
        attributedText.addAttributes([NSFontAttributeName: myLabel!.font], range: NSMakeRange(0, (myLabel!.attributedText?.string.characters.count)!))
    
        // Create instances of NSLayoutManager, NSTextContainer and NSTextStorage
        let layoutManager = NSLayoutManager()
        let textContainer = NSTextContainer(size: CGSize(width: (myLabel?.frame.width)!, height: (myLabel?.frame.height)!+100))
        let textStorage = NSTextStorage(attributedString: attributedText)
    
        // Configure layoutManager and textStorage
        layoutManager.addTextContainer(textContainer)
        textStorage.addLayoutManager(layoutManager)
    
        // Configure textContainer
        textContainer.lineFragmentPadding = 0.0
        textContainer.lineBreakMode = myLabel!.lineBreakMode
        textContainer.maximumNumberOfLines = myLabel!.numberOfLines
        let labelSize = myLabel!.bounds.size
        textContainer.size = labelSize
    
        // get the index of character where user tapped
        let indexOfCharacter = layoutManager.characterIndex(for: tapLocation, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
    

提交回复
热议问题