背景和目标
Goal:我想旋转和翻转UITextView
. (Why: see my 上一个问题 https://stackoverflow.com/questions/28544714/how-do-you-make-a-vertical-text-uilabel-and-uitextview-for-ios-in-swift)
Problem:如果我直接在UITextView
,由于某种未知的原因,文本布局变得混乱。
解决方案:放在UITextView
in a UIView
容器,然后对容器进行转换。
新问题:旋转视图上的自动布局(或任何类型的布局)变为非常头疼 https://stackoverflow.com/questions/30841064/are-rotated-views-compatible-with-auto-layout.
建议的解决方案:制作一个子类UIView
充当旋转和翻转的附加容器UIView
。然后自动布局应该在这个自定义视图上工作。
目前的问题
当所有内容第一次出现时它就会起作用(UITextView
有黄色背景):
但是当方向发生变化时,会发生以下情况(蓝色是子类UIView
背景,在IB中设置):
如果我禁用rotationView.addSubview(textView)
线,然后旋转容器视图(红色)可以很好地重新定位自身,即使方向发生变化:
所以问题一定出在我添加的位置UITextView
。但我该怎么做呢?
Code
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()
进行转换。但这不是我的第一选择,因为这样做可能会降低性能。