在方向更改时维护UITextView的contentOffset

时间:2015-12-04 13:00:02

标签: ios uitextview

是否可以更改UITextView的内容偏移量,以便当用户从纵向移动到横向(反之亦然)时,对它们可见的文本保持不变?

因此,如果用户处于(纵向模式)

....some text....
....some text2....
....I'm here.... //this is the visible area
....more text....

转移到横向,它应该是

....some text....some text2....
....I'm here....more text.... //this is the visible area
.....

UITextView不可编辑但可滚动。

1 个答案:

答案 0 :(得分:4)

这里有一个简短的,自包含的,可编辑的例子:

import UIKit

class ViewController: UIViewController {

    var textView: UITextView!
    var percentOfScroll:CGFloat = 0

    override func viewDidLoad() {

        self.textView = UITextView(frame: CGRectZero)

        self.textView.layer.borderColor = UIColor.blackColor().CGColor
        self.textView.layer.borderWidth = 1
        self.textView.editable = false

        self.textView.text = "Lorem ipsum... some longish text"

        self.view.addSubview(self.textView)

        let leftConstraint = NSLayoutConstraint(item: self.textView, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1, constant: 10)
        let rightConstraint = NSLayoutConstraint(item: self.textView, attribute: .Trailing, relatedBy: .Equal, toItem: self.view, attribute: .Trailing, multiplier: 1, constant: -10)
        let topConstraint = NSLayoutConstraint(item: self.textView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: 44)
        let centerConstraint = NSLayoutConstraint(item: self.textView, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1, constant: 0)

        self.textView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addConstraints([leftConstraint, rightConstraint, topConstraint, centerConstraint])
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        let contentSize = self.textView.contentSize
        let newOffset = contentSize.height * percentOfScroll

        self.textView.contentOffset = CGPoint(x: 0, y: newOffset)
    }

    override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {

        super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)

        let contentSize = self.textView.contentSize
        let contentOffset = self.textView.contentOffset

        self.percentOfScroll = contentOffset.y / contentSize.height
    }

}

我们的想法是在轮换之前获取滚动内容相对于其高度的数量(viewWillTransitionToSize)并使用它计算新的contentOffset之后(viewDidLayoutSubviews也会在尺寸更改后调用)。

请记住,这并没有给出100%的精确结果,但我还没有能够提出更好的结果,也许这对你来说已经足够了。