我正在使用主视图控制器上带有按钮的视图。直到最近我开始弄乱约束以使外观看起来更好时,我的按钮才能正常工作。在调整了一些大小和约束后,按钮才停止工作。
这是我的设置: 我有一个自定义视图,在其中设置了3个按钮,并向它们添加了约束
override init(frame: CGRect) {
super.init(frame: frame)
let buttonSize: CGFloat = 90.0
addSubview(photoButton)
photoButton.anchor(top: nil, leading: nil, bottom: bottomAnchor, trailing: nil, padding: .init(top: 0, left: 0, bottom: 0, right: 0), size: .init(width: buttonSize, height: buttonSize))
photoButton.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
addSubview(homeButton)
homeButton.anchor(top: nil, leading: nil, bottom: bottomAnchor, trailing: photoButton.leadingAnchor, padding: .init(top: 0, left: 0, bottom: 0, right: 20), size: .init(width: buttonSize, height: buttonSize))
addSubview(profileButton)
profileButton.anchor(top: nil, leading: photoButton.trailingAnchor, bottom: bottomAnchor, trailing: nil, padding: .init(top: 0, left: 20, bottom: 0, right: 0), size: .init(width: buttonSize, height: buttonSize))
}
在主视图控制器中,我为按钮添加了目标,以便在点击按钮时调用这些函数。
let buttonView = HomeBottomControlsView()
我认为已加载
buttonView.homeButton.addTarget(self, action: #selector(openTrending), for: .touchUpInside)
buttonView.profileButton.addTarget(self, action: #selector(openProfile), for: .touchUpInside)
view.addSubview(overallStackView)
view.addSubview(buttonView)
overallStackView.translatesAutoresizingMaskIntoConstraints = false
overallStackView.anchor(top: view.safeAreaLayoutGuide.topAnchor, leading: view.leadingAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, trailing: view.trailingAnchor)
overallStackView.isLayoutMarginsRelativeArrangement = true
overallStackView.layoutMargins = .init(top: 10, left: 12, bottom: 95, right: 12)
buttonStackView.anchor(top: overallStackView.bottomAnchor, leading: view.leadingAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, trailing: view.trailingAnchor, padding: .init(top: 0, left: 0, bottom: 0, right: 0), size: .init(width: 0, height: 0))
以前,这些按钮一直有效,直到我开始尝试使用自动布局约束。现在,我似乎无法再点击按钮了。
我在其他问题中读到,由于初始帧的问题,有时按钮无法正常工作。这是这里的问题吗?
答案 0 :(得分:2)
此视图已经占据了整个THREE.DoubleSide
view
,并且您将overallStackView.anchor(top: view.safeAreaLayoutGuide.topAnchor, leading: view.leadingAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, trailing: view.trailingAnchor)
的topAnchor设置为buttonStackView
的底部锚点。这就是为什么框架放置不正确的原因。您需要同时更改overallStackView
和buttonStackView
的约束,以便它们不会相互重叠