UIKit:旋转视图90度并保持边缘贴合的可扩展实现方法
更新说明
我尝试调整图层锚点为(0,0),旋转后将视图平移回(0,0)位置,但仍未解决文本提前换行的问题,设置右侧(旋转后的底部)内容内边距也无效。相关代码如下:
textView.frame = CGRect(x: 0, y: 0, width: view.bounds.height, height: view.bounds.width) print(textView.frame) textView.setAnchorPoint(CGPoint(x: 0, y: 0)) textView.transform = CGAffineTransform(rotationAngle: (CGFloat)(Double.pi/2)); print(textView.frame) textView.transform = textView.transform.translatedBy(x: 0, y: -(view.bounds.width)) print(textView.frame) textView.contentInset = UIEdgeInsets(top: 0, left: height, bottom: 0, right: 0)

原始问题
我希望将子视图中唯一的UIView顺时针旋转90度,同时保持其边界贴合屏幕边缘——位于Navigation Bar下方、Tab Bar上方,左右两侧贴合屏幕边缘。
通常实现视图边缘贴合有两种方式:
- 将
translatesAutoresizingMaskIntoConstraints设为true,再设置subview.frame = view.bounds - 将
translatesAutoresizingMaskIntoConstraints设为false,添加top、bottom、leading、trailing四个锚点约束与父视图对应锚点绑定
正常情况下效果如下:
但如果要在旋转视图的同时保持上述边缘贴合效果,该如何实现?预期效果如下:
当前尝试及问题
以下是我旋转UITextView90度的代码(当前无Tab Bar,不影响问题):
var textView = UITextView() view.addSubview(textView) textView.translatesAutoresizingMaskIntoConstraints = true textView.transform = CGAffineTransform(rotationAngle: (CGFloat)(Double.pi/2)); textView.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)
旋转后视图未贴合预期边缘,被Navigation Bar遮挡:
如果先设置frame再旋转,视图会完全消失:
尝试给textView的y坐标设置固定值:
textView.frame = CGRect(x: 0, y: 100, width: view.bounds.width, height: view.bounds.height)
结果文本在到达底部边缘前就提前换行:
尝试添加锚点约束并将translatesAutoresizingMaskIntoConstraints设为false:
constraints.append(contentsOf: [ textView.topAnchor.constraint(equalTo: view.topAnchor), textView.bottomAnchor.constraint(equalTo: view.bottomAnchor), textView.leadingAnchor.constraint(equalTo: view.leadingAnchor), textView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
结果仍是空白屏幕。
除上述尝试外,我还做了很多零散调整,但均为临时解决方案,不具备可扩展性——比如设备旋转为横屏时,视图会完全错乱。
因此我想请教:正确且可扩展的实现方式是什么?我需要旋转后的textView可向左滚动延伸,并能在任意设备尺寸及屏幕方向下正确适配。
我知道这可能与锚点相关,但我需要的是视图本身贴合边缘,而非像旋转UIImage那样仅调整内容显示。具体步骤该如何实现?
感谢解答。
内容的提问来源于stack exchange,提问作者yaozhang
相关产品推荐
相关产品推荐

