我正在制作一个注释 View ,其中包括一个自定义按钮。当点击这个按钮时,它应该执行一些操作。首先我会尝试将其打印出来。现在,注释 View 正在关闭,但不打印任何内容。它关闭是因为我做了一个button.removeFromSuperview。 下面是它的外观,只关注按钮
class CustomAnnotation: MKPinAnnotationView, MKMapViewDelegate, CLLocationManagerDelegate {
let infoButton : UIButton = UIButton.init(frame:CGRect(x: 250, y: -300, width: 40, height: 40))
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(true, animated: animated)
if(selected) {
infoButton.setImage(UIImage(named:"home.png"), for: .normal)
infoButton.addTarget(self, action: #selector(sayHello), for:.touchUpInside)
self.addSubview(infoButton)
} else {
infoButton.removeFromSuperview()
}
func sayHello(sender: UIButton!) {
print("I should print something...")
}
}
自定义注释 View 中的所有内容看起来都很棒。 我在 viewForAnnotation 函数中将 CustomAnnotation 类调用到我的 Viewcontroller 中。
最佳答案
它正在执行 .removeFromSuperview() ,因为您将 selected 设置为 false,因此您的 if 语句总是失败,并转到 else。
您的线路: super.setSelected(false,animated:animated)
应该是: super.setSelected(选中, 动画: 动画)
关于ios - 自定义注释中以编程方式按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41859119/