Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine where UITextView will truncate string

I have a UITextView with a long string. The text views size is determined by autolayout, and it is set to tail truncate the text. It looks like this:

UITextView truncating

How can I determing the range of the string that is displayed and the range that is truncated away?

like image 774
Wiingaard Avatar asked Nov 08 '22 14:11

Wiingaard


1 Answers

try this

class ViewController: UIViewController ,NSLayoutManagerDelegate{

@IBOutlet weak var textView: UITextView!
var range :NSRange!
override func viewDidLoad() {
    super.viewDidLoad()


    textView.textContainer.layoutManager?.delegate = self
    let str = textView.text as NSString
    //Regardless of the repeated string
    range = str.rangeOfString("cillium adipisicing")
    print(range)


}

// Invoked while determining the soft line break point.  When NO, NSLayoutManager tries to find the next line break opportunity before charIndex
func layoutManager(layoutManager: NSLayoutManager, shouldBreakLineByWordBeforeCharacterAtIndex charIndex: Int) -> Bool{

    // charIndex is in the string or not
    if range.location != NSNotFound && NSLocationInRange(charIndex, NSRange(location: range.location + 1, length: range.length - 1 )) {
        print("range of string is truncated -> charIndex is \(charIndex)")
    }
    return  true
}
}

but it's limited to BreakLineByWord if words without " " and truncated ,charIndex is 0

hope it be helpful :)

like image 194
Wilson XJ Avatar answered Nov 14 '22 22:11

Wilson XJ