ios - 自定义注释中以编程方式按钮

标签 ios swift mapkit

我正在制作一个注释 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/

相关文章:

ios - swift 3 录制视频但不录制音频

android - 首页英雄背景图像在移动设备上缩放不当

ios - 如何在sqlite中使用循环从特定列获取名称

使用自动布局快速增长 UITextView

Swift 将 Integer 转换为 Int

swift - 在 for 循环中更改 SKNode 子节点的属性

macos - 如何启用 MKMapView 3D View ?

iphone - iOS 配置文件过期

swift - 如何在 MKAnnotationView 的标注中自定义标题/副标题字体或只是隐藏它们?

ios - MKMapView:偏移贴图使标注可见