我仍在学习视图约束的工作方式,并且自iOS 7以来,似乎已经引入和弃用了许多相关属性。同时,我的想法仍然与iOS 7之前的AutoLayout绑定,因此下面的代码可能是不必要的概念组合。
我正在尝试将MKUserTrackingButton放置在viewcontroller.view的底部。这是我所拥有的:
func setUpUserLocationButton() {
let userLocButton = MKUserTrackingButton(mapView: self.mapView)
userLocButton.backgroundColor = .white
userLocButton.frame.origin.x = self.view.frame.width - userLocButton.frame.size.width
userLocButton.frame.origin.y = self.view.frame.height - userLocButton.frame.size.height
userLocButton.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin]
self.mapView.addSubview(userLocButton)
userLocButton.translatesAutoresizingMaskIntoConstraints = false
let margins = self.view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
userLocButton.rightAnchor.constraint(equalTo: margins.rightAnchor),
userLocButton.bottomAnchor.constraint(equalTo: margins.bottomAnchor),
])
setGenericShadow(subView: userLocButton)
}
在风景中,一切看起来都是正确的。在纵向模式下,按钮右侧仍然存在问题。它不是“安全地”放置在超级视图(视图控制器视图)中。
我在做什么错了?
风景
肖像
更新:我已经将代码更新为可以正常运行的代码。但是我不确定这是否正确,尽管可以工作吗?见下文:
override func viewLayoutMarginsDidChange() {
setUpUserLocationButton()
}
func setUpUserLocationButton() {
if(userTracker == nil){
userTracker = MKUserTrackingButton(mapView: self.mapView)
userTracker!.backgroundColor = .white
self.mapView.addSubview(userTracker!)
}
userTracker!.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin]
userTracker!.frame.origin.x = self.view.frame.width - userTracker!.frame.size.width
userTracker!.frame.origin.y = self.view.frame.height - userTracker!.frame.size.height
if UIApplication.shared.keyWindow!.safeAreaInsets.right == 0 {
additionalSafeAreaInsets.right = 44
}
userTracker!.translatesAutoresizingMaskIntoConstraints = false
let margins = self.view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
userTracker!.rightAnchor.constraint(equalTo: margins.rightAnchor),
userTracker!.bottomAnchor.constraint(equalTo: margins.bottomAnchor),
])
setGenericShadow(subView: userTracker!)
}