背景和目标
目标:我想要旋转和翻转一个UITextView
。(为什么:请参考我的上一个问题)
问题:如果我直接对UITextView
进行变换,由于某种未知原因,文本布局会被搞乱。
解决方案:将UITextView
放入一个UIView
容器中,然后在容器上进行变换。
新问题:对旋转的视图进行自动布局(或任何类型的布局)成为一个主要的头痛。
建议的解决方案:创建一个UIView
的子类,作为旋转和翻转UIView
的额外容器。然后,Auto Layout应该可以在这个自定义视图上正常工作。
当前问题
当所有内容首次出现时它可以工作(UITextView
具有黄色背景):
但是当屏幕方向改变时,以下情况会发生(蓝色是在IB中设置的子类化UIView
背景):
rotationView.addSubview(textView)
这一行,那么旋转容器视图(红色)在方向改变时仍然可以很好地重新定位:
所以问题肯定是我添加 UITextView
的位置有问题。但是我该怎么做呢?
代码
class MongolTextView: UIView {
// properties
var rotationView: UIView!
var textView: UITextView!
// This method gets called if you create the view in the Interface Builder
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// This method gets called if you create the view in code
override init(frame: CGRect){
super.init(frame: frame)
self.setup()
}
override func awakeFromNib() {
super.awakeFromNib()
self.setup()
}
func setup() {
rotationView = UIView(frame: self.frame)
rotationView.backgroundColor = UIColor.redColor()
self.addSubview(rotationView)
textView = UITextView(frame: CGRectZero)
textView.backgroundColor = UIColor.yellowColor()
textView.text = "This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text "
}
override func layoutSubviews() {
super.layoutSubviews()
// set the size of the rotation container view
let width = self.bounds.width
let height = self.bounds.height
rotationView.frame = CGRect(origin: CGPoint(x: CGFloat(0), y: CGFloat(0)), size: CGSize(width: height, height: width))
textView.frame = rotationView.bounds // Problem lines here???
rotationView.addSubview(textView) // Problem lines here???
// rotate, translate, and flip the container view
var rotation = CGAffineTransformMakeRotation(CGFloat(-M_PI_2))
// the following translation repositions the top left corner at the origin of the superview
var translation = CGAffineTransformMakeTranslation((rotationView.bounds.height / 2)-(rotationView.bounds.width / 2), (rotationView.bounds.width / 2)-(rotationView.bounds.height / 2))
var rotationAndTranslation = CGAffineTransformConcat(rotation, translation)
var transformPlusScale = CGAffineTransformScale(rotationAndTranslation, CGFloat(-1), CGFloat(1))
rotationView.transform = transformPlusScale
}
}
如果我无法让它工作...
虽然我目前遇到了难题,但我的下一个计划是覆盖 drawRect()
来执行转换。不过这不是我的首选,因为据说这样做会降低性能。
self.bounds
的width
和height
保持不变。关于变换被应用两次的好点子。但我不太确定如何解决这个问题。 - SuragchUITextView
的文本在应用旋转时需要改变吗?您能否只快照它并旋转快照呢? - NickUITextView
可滚动的属性。在我看来,创建位图可能会导致其无法滚动。 - Suragchself
和子视图之间始终需要交换宽度和高度(对于任何方向),因为子视图相对于self
旋转了90度。 - Suragch