[英]Centering UILabel not working?
只需centerYAnchor
編程方式設置centerXAnchor
和centerYAnchor
:
view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant:0).isActive = true
label.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant:0).isActive = true
label.widthAnchor.constraint(equalToConstant: 50.0).isActive = true
這應該對你有幫助
你應該horizontally in container, Vertically in container, fixed width and fixed heigh
,這四個限制你的label
。 這四個限制將始終將您的標簽保持在屏幕的中心!
試試這個而不添加任何約束
label.center = CGPointMake((self.view.frame.size.width - label.frame.size.width) / 2 , (self.view.frame.size.height - label.frame.size.height) / 2);
這是因為視圖使用約束。 如果要使用center
屬性,則應該在視圖具有布局本身后設置值,因此在viewDidLayoutSubviews
或layoutSubviews
方法中(第一個用於視圖控制器,第二個用於視圖)。
另一種方法是設置約束。
嘗試添加label.sizeToFit()
應該有所幫助
嘗試這個。 它為我工作
var label = UILabel(frame: CGRectMake(self.view.frame.origin.x + self.view.frame.size.width/2, self.view.frame.origin.y + self.view.frame.size.height/2, 200, 21))
label.textAlignment = NSTextAlignment.Center
label.text = "I'am a test label"
label.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2)
self.view.addSubview(label)
我需要刪除前導和尾隨約束。 我將它水平居中放在視圖中,並將其垂直間距設置為相對於另一個視圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.