不知道底边的边缘是什么意思,如果你说的是安全区域布局指南,那么你可以使用
NSLayoutConstraint.activate([buttonRound.bottomAnchor.constraint(equalTo:view!.safeAreaLayoutGuide.bottomAnchor),
buttonRound.widthAnchor.constraint(equalToConstant: 100),
buttonRound.heightAnchor.constraint(equalToConstant:50)])
代码中的几个问题,
- 你已经应用了两次相同的约束,这对我来说没有逻辑意义
buttonRound.bottomAnchor.constraint(equalTo: view!.bottomAnchor),
buttonRound.bottomAnchor.constraint(equalTo: view!.bottomAnchor)
-
您使用view! 强制展开视图我不确定它是否是 ViewController 的视图,如果它是 ViewController 的视图,您不需要强制展开它,因为它本质上是一个隐含的可选,所以您应该能够改为view.safeAreaLayoutGuide。
-
通过代码访问视图,就好像它是可选的一样,使用 view?.addSubview(buttonRound)、view!.bottomAnchor 之类的语句,因为我不确定它是哪个视图,如果你确定它是可选的,我建议使用带有 @ 的安全展开987654327@, guard let 而不是 !
if let view = view {
view.addSubview(buttonRound)
buttonRound.setTitle("Jump", for: .normal)
buttonRound.addTarget(self, action: #selector(roundhandle), for: .touchUpInside)
buttonRound.backgroundColor = .red
buttonRound.layer.cornerRadius = 5
buttonRound.layer.borderWidth = 1
buttonRound.layer.borderColor = UIColor.white.cgColor
buttonRound.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([buttonRound.bottomAnchor.constraint(equalTo:view.safeAreaLayoutGuide.bottomAnchor),
buttonRound.widthAnchor.constraint(equalToConstant: 100),
buttonRound.heightAnchor.constraint(equalToConstant:50)])
}
编辑:正如下面 OP 所评论的,他看到了错误
“SafeAreLayoutGude”仅适用于 iOS 11.0 或更新版本
OP 必须使用低于 iOS 11 的部署目标,并且由于 OP 没有在评论中回复我的问题,我正在更新答案以支持低于 iOS 11.0
if let view = view {
view.addSubview(buttonRound)
buttonRound.setTitle("Jump", for: .normal)
buttonRound.addTarget(self, action: #selector(roundhandle), for: .touchUpInside)
buttonRound.backgroundColor = .red
buttonRound.layer.cornerRadius = 5
buttonRound.layer.borderWidth = 1
buttonRound.layer.borderColor = UIColor.white.cgColor
buttonRound.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([buttonRound.widthAnchor.constraint(equalToConstant: 100),
buttonRound.heightAnchor.constraint(equalToConstant:50)])
if #available(iOS 11.0, *) {
buttonRound.bottomAnchor.constraint(equalTo:view.safeAreaLayoutGuide.bottomAnchor).isActive = true
}
else {
buttonRound.bottomAnchor.constraint(equalTo:view.bottomAnchor).isActive = true
}
}
不太确定您正在构建/维护哪种应用程序,iOS 11 对我来说似乎太旧了,检查您是否真的需要支持这么旧的 iOS 版本,将项目设置中的 iOS 部署目标值更改为避免这样的多个兼容问题。