ios - 确定 UITextView 将截断字符串的位置

标签 ios string swift autolayout uitextview

我有一个带有长字符串的 UITextView。 TextView 大小由自动布局决定,并设置为尾部截断文本。它看起来像这样:

UITextView truncating

如何确定显示的字符串范围和被截断的范围?

最佳答案

试试这个

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
}
}

但仅限于 BreakLineByWord 如果没有 ""的单词被截断,charIndex 为 0

希望对您有所帮助:)

关于ios - 确定 UITextView 将截断字符串的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37523529/

相关文章:

ios - NSAttributedString 中字距调整的不一致行为

c - *char 值在函数上改变

ios - 如何创建没有矩形边界的自定义 View ,并启用手势识别

ios - 在标签上打印 Instagram 帖子回复时出现问题

ios - PerformSegueWithIdentifier 不工作 swift

iphone - 应用未运行时推送通知数据?

ios - AVAudioPlayer iOS 错误

ios - DrawRect 覆盖 View 的属性

c++ - 字符串 find_first 不更新字符串

php - 我什么时候应该使用 mb_strpos();在 strpos() 之上;?