使用Swift编程在按钮上动态添加约束条件

3

我想在Swift中向UIMapView添加一个位置查找器按钮,但是我无法为其添加约束。目前,我的任何约束都似乎不起作用,该按钮停留在左上角。以下是我的代码:

override func loadView() 
{
mapView = MKMapView()
view = mapView

let margins = view.layoutMarginsGuide

let locationButton = UIButton()
mapView.addSubview(locationButton)

locationButton.setTitle("find location", for: [])
locationButton.backgroundColor = UIColor.lightGray().withAlphaComponent(0.6)
locationButton.layer.cornerRadius = 3
locationButton.sizeToFit()
locationButton.translatesAutoresizingMaskIntoConstraints = true

locationButton.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: 20).isActive = true
locationButton.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true
locationButton.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
}

任何帮助都将不胜感激。

locationButton.translatesAutosizingMaskIntoContraints = false,和locationButton.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: -50).isActive = true,似乎解决了我的问题。 - user6537725
1
如果您已经找到了解决自己问题的方法,请将其添加为答案,以便未来的谷歌搜索者可以受益。 :) - Code Different
1个回答

1

设置

    locationButton.translatesAutoresizingMaskIntoConstraints = false

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接