Scroll to bottom of UITextView erratic in iOS 7

前端 未结 9 1699
无人及你
无人及你 2020-12-01 04:58

The following code will work fine in iOS < 7.0. In iOS 7 the scrolling will be choppy and erratic while the UITextView is updating. I\'m not sure if this is a bug in iO

9条回答
  •  旧时难觅i
    2020-12-01 05:26

    For those who are using Swift, I post here the same answer as RawMean (thanks again!). As I wrote this (dec. 2014), the problem still exist in iOS 8.1 and his solution work perfectly...

    var textView: UITextView!
    var textStorage: NSTextStorage!
    var layoutManager: NSLayoutManager!
    var textContainer: NSTextContainer!
    
    
    override func viewDidLoad() {
        textStorage = NSTextStorage()
        layoutManager = NSLayoutManager()
        textStorage.addLayoutManager(layoutManager)
    
        let newTextViewRect = view.bounds
        let containerSize = CGSize(width: newTextViewRect.width, height: CGFloat.max)
    
        textContainer = NSTextContainer(size: containerSize)
        layoutManager.addTextContainer(textContainer)
    
        textView = UITextView(frame: newTextViewRect, textContainer: textContainer)
    
        textView.delegate = self
        view.addSubview(textView)
    
    }
    
    override func viewDidLayoutSubviews() {
        textView.frame = view.bounds
    }
    

    and I used the scrollRangeToVisible method to scroll smoothly at the bottom as text is added...

    let length = countElements(textView.text)
    let range:NSRange = NSMakeRange(length - 1, 1)
    textView.scrollRangeToVisible(range)
    

提交回复
热议问题