我正在尝试在viewDidLoad
函数中对标签进行编码。标签正在显示,但是我现在使用的代码不会影响位置。我正在尝试在viewDidLoad
函数中编写所有代码。您可以在下面看到屏幕截图。
override func viewDidLoad() {
super.viewDidLoad()
let backbutton = UILabel()
backbutton.backgroundColor = UIColor.orange
backbutton.translatesAutoresizingMaskIntoConstraints = false
backbutton.widthAnchor.constraint(equalToConstant: 300).isActive = true
backbutton.heightAnchor.constraint(equalToConstant: 300).isActive = true
backbutton.centerXAnchor.constraint(equalTo: backbutton.centerXAnchor, constant: 100).isActive = true
backbutton.centerYAnchor.constraint(equalTo: backbutton.centerYAnchor, constant: 300).isActive = true
view.addSubview(backbutton)
}
答案 0 :(得分:3)
这是将label
与center
的{{1}}对齐的方式,
view
以编程方式设置let backbutton = UILabel()
view.addSubview(backbutton)
backbutton.backgroundColor = UIColor.orange
backbutton.translatesAutoresizingMaskIntoConstraints = false
backbutton.widthAnchor.constraint(equalToConstant: 300).isActive = true
backbutton.heightAnchor.constraint(equalToConstant: 300).isActive = true
backbutton.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true
backbutton.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 0).isActive = true
时,请确保在应用constraints
之前将view
添加到super/parent
view
中。其次,在下面的几行中,您告诉constraints
标签使其中心与其自身对齐(即 backbutton.centerXAnchor.constraint(equalTo:backbutton.centerXAnchor )。
backButton
由于要使其backbutton.centerXAnchor.constraint(equalTo: backbutton.centerXAnchor, constant: 100).isActive = true
backbutton.centerYAnchor.constraint(equalTo: backbutton.centerYAnchor, constant: 300).isActive = true
和vertically
与其horizontally
居中对齐,因此应将parent view
center
设置为等于constraints
如下,
parent view
答案 1 :(得分:2)
尝试一下!
self.view.setNeedsUpdateConstraints()
self.view.layoutIfNeeded()
答案 2 :(得分:0)
尝试改用CGRect:
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
let xPostion:CGFloat = screenWidth - 150 //150 is half of view's width
let yPostion:CGFloat = screenHeight - 150 //150 is half of view's height
let buttonWidth:CGFloat = 300
let buttonHeight:CGFloat = 300
backbutton.frame = CGRect(x:xPostion, y:yPostion, width:buttonWidth, height:buttonHeight)
除了屏幕宽度/高度,您还可以尝试使用以下方法获取超级视图的宽度:
self.view.frame.width
self.view.frame.height