gpt4 book ai didi

ios - 在方向更改时维护 UITextView 的 contentOffset

转载 作者:可可西里 更新时间:2023-11-01 05:40:31 24 4
gpt4 key购买 nike

是否可以更改 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 不可编辑但可滚动。

最佳答案

这里有一个简短的、独立的、可编译的例子:

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% 精确的结果,但我还没有想出更好的办法,也许这对你来说就足够了。

关于ios - 在方向更改时维护 UITextView 的 contentOffset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34088993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com