【发布时间】:2018-04-06 18:41:10
【问题描述】:
我有一个以编程方式创建并设置了约束的 UILabel:
NSLayoutConstraint.activate([
theLabel.topAnchor.constraint(equalTo: otherView.topAnchor),
theLabel.leadingAnchor.constraint(equalTo: otherView.trailingAnchor, constant: otherView.frame.width/2),
theLabel.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5),
theLabel.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.2),
])
然后我想将标签添加到场景中:
theLabel.transform = CGAffineTransform(scaleX: 0.0001, y: 0.0001)
theLabel.isHidden = false
UIView.animate(withDuration: 0.8, delay: 0.0, options: UIViewAnimationOptions(), animations: {
self.theLabel.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) //or CGAffineTransform.identity
}, completion: nil)
但是标签是左对齐的,它从中心开始增长,所以我更改了锚点来修复问题,但这导致标签出现在比应有的更靠右的位置。 (我理解这是因为我现在在视图的左侧而不是中心来描述它的位置)
theLabel.layer.anchorPoint = CGPoint(x: 0.0, y: 0.5)
我尝试在设置 anchorPoint 后只替换它的框架和中心点(另外,我先尝试了框架,然后是中心),但是这些解决方案都没有对应用程序中的视图显示方式产生任何影响:
let oldFrame = theLabel.frame
theLabel.layer.anchorPoint = CGPoint(x: 0.0, y: 0.5)
theLabel.frame = oldFrame
let oldCenter = theLabel.center
theLabel.layer.anchorPoint = CGPoint(x: 0.0, y: 0.5)
theLabel.center = oldCenter
任何其他建议或解释可以帮助我了解如何在更改其锚点的同时有效地保留视图的位置?谢谢大家!
【问题讨论】:
标签: ios swift uilabel nslayoutconstraint cgaffinetransform