2017-10-13 71 views
0

我有一个带标签的容器视图,容器视图以超级视图大小的一半以编程方式添加到超视图的下半部分。我设置的大小是这样的:Swift:如何找出容器视图的大小并以编程方式在中心放置一个标签?

testView.frame.size = CGSize(width: view.bounds.width, height: view.bounds.height/2) 

enter image description here

(橙色广场是containerView和多数民众赞成在我想打标签 - 容器视图中心)

这样它就是superview的一半大小。 现在我想通过编程的方式将标签放在容器视图的正中间。实际上它应该用CGAffineTransform动画并移动到中心,但为了我的问题,它并不重要。

我已经尝试了几件事情,但即使像self.testView.midX/midY这样的简单解决方案也不起作用。它不居中,或者标签放置在容器外的某处。

我试图让意见宽度和高度:

let timerViewWidth = self.timerView.bounds.width 
let timerViewHeight = self.timerView.bounds.height 

和除以2,既要得到testView的正中心,但是当我使用这些值的标签也被放在别的地方。

如何以编程方式将标签居中放在容器视图中?

+1

你应该看看自动布局和约束,但如果你真的不想......你可以使用'testView.center = view.center' – DonMag

回答

0

只需使用autolayout将UILabel添加到您的容器视图(我将调用containerView)。

let label = UILabel() 
label.translatesAutoresizingMaskIntoConstraints = false 
//configure label the label as needed 
containerView.addSubview(label) 

containerView.addConstraint(NSLayoutConstraint(item: label, attribute: .centerX, relatedBy: .equal, toItem: containerView, attribute: .centerX, multiplier: 1.0, constant: 0.0)); 
containerView.addConstraint(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: containerView, attribute: .centerY, multiplier: 1.0, constant: 0.0)); 

如果你不想使用自动布局只是做@DonMag建议

testView.center = containerView.center 

还要确保您添加testView为containerView子视图而不是其他视图...

相关问题