简体   繁体   中英

Add constraints to a button programmatically using Swift

I am struggling to add constraints to a location finder button I want to add to a UIMapView in swift, so far none of my constraints seem to be working and the button is stuck in the top left hand corner, here is my code:

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
}

any help will be sincerely appreciated.

    locationButton.translatesAutoresizingMaskIntoConstraints = false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM