[英]Why is my UIButton target action not being called?
我正在使用 Google 地图 API,并且我创建了一个 UIButton 以放置在 map 视图的顶部。 在 UIButton 里面,我插入了一个 UIImageView。 出于某种原因,在我将目标操作添加到 UIButton 后,选择器方法没有被调用。 以下是构建应用程序时元素外观的示例:
这是我的选择器方法:
@objc func goToListView() {
print("Go to list view!")
}
这是我的 UIButton 代码:
func configureReturnToListViewItem() {
view.addSubview(returnToListViewItem)
returnToListViewItem.backgroundColor = .white
returnToListViewItem.layer.cornerRadius = 25
returnToListViewItem.clipsToBounds = true
returnToListViewItem.isUserInteractionEnabled = true
returnToListViewItem.translatesAutoresizingMaskIntoConstraints = false
returnToListViewItem.heightAnchor.constraint(equalToConstant: 50).isActive = true
returnToListViewItem.widthAnchor.constraint(equalToConstant: 50).isActive = true
returnToListViewItem.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 25).isActive = true
returnToListViewItem.topAnchor.constraint(equalTo: view.topAnchor, constant: 50).isActive = true
returnToListViewItem.addTarget(self, action: #selector(goToListView), for: .touchUpInside)
}
这是 UIButton 中的图像代码,以防万一:
func configureReturnToListViewImage() {
returnToListViewItem.addSubview(returnToListViewImage)
let image = UIImage(named: "list")
returnToListViewImage.image = image
returnToListViewImage.contentMode = .scaleAspectFill
returnToListViewImage.clipsToBounds = true
returnToListViewImage.layer.masksToBounds = true
returnToListViewImage.translatesAutoresizingMaskIntoConstraints = false
returnToListViewImage.heightAnchor.constraint(equalToConstant: 20).isActive = true
returnToListViewImage.widthAnchor.constraint(equalToConstant: 20).isActive = true
returnToListViewImage.centerXAnchor.constraint(equalTo: returnToListViewItem.centerXAnchor).isActive = true
returnToListViewImage.centerYAnchor.constraint(equalTo: returnToListViewItem.centerYAnchor).isActive = true
}
我已经尝试过点击手势,以及将视图 controller 中的所有元素的isUserInteractionEnabled设置为true 。 我希望得到一些指导!
编辑:我的问题是由于早期配置导致的不可见导航栏。 在大多数情况下,其他答案是正确的 - 因此,如果它们适用于您的情况,请也使用这些答案。
似乎returnToListViewImage
掩盖了returnToListViewItem
。 尝试不使用returnToListViewImage
以查看它是否触发了目标。 如果是,您可以在returnToListViewImage
上添加轻击手势并将目标设置为goToListView
不要忘记将returnToListViewImage
设置为isUserIteractionEnabled
为true
,它的工作原理相同。
更好的方法:您可以直接将图像设置为 UIButton 类型returnToListViewItem
,就像这样,这将只需要一行而不是您给出的整个 function 。
returnToListViewItem.setImage(UIImage(named: "list"), for: .normal)
我在运行我的应用程序后使用视图调试器找到了我的问题的答案。 在我的具体情况下,我的不可见导航栏覆盖了按钮,这阻止了与导航栏下方的任何内容的任何交互。 我所要做的就是将这行代码添加到我的viewDidLoad() function 中:
self.navigationController?.setNavigationBarHidden(true, animated: false)
视图调试器是救命稻草!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.