我有以下结构:
我希望将标签旋转270度以实现此目的:
通过CGAffineTransform.rotated下一步:
credentialsView.text = "Developed in EVNE Developers"
credentialsView.transform = credentialsView.transform.rotated(by: CGFloat(Double.pi / 2 * 3))
但不是预期的结果,我得到了以下内容:
那么,旋转视图的正确方法是什么,而不是改变它的方形边界或它做什么,并保持从屏幕边缘前进16px?
我尝试了很多方法,包括扩展UILabel以直接在故事板中查看旋转,在带有前导的stackview中放置数据视图,它也没有帮助等等。
答案 0 :(得分:3)
这是一个解决方案,它将以适当的方式旋转您的标签,然后返回垂直水平状态。在运行代码之前,在storyboard中为标签设置约束:导致16和垂直居中。
现在看看:
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
// Your leading constraint from storyboard, initially set to 16
@IBOutlet weak var leadingConstraint: NSLayoutConstraint!
var isHorizontal: Bool = true
var defaultLeftInset: CGFloat = 16.0
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
label.text = "This is my label"
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapAction)))
}
@objc func tapAction() {
if self.isHorizontal {
// Here goes some magic
// constraints do not depend on transform matrix,
// so we have to adjust a leading one to fit our requirements
leadingConstraint.constant = defaultLeftInset - label.frame.width/2 + label.frame.height/2
self.label.transform = CGAffineTransform(rotationAngle: .pi/2*3)
}
else {
leadingConstraint.constant = defaultLeftInset
self.label.transform = .identity
}
self.isHorizontal = !self.isHorizontal
}
}