我在mapView上实现了一个自定义calloutView,我正在尝试从自定义calloutView实现操作按钮。我无法找到相对于calloutViews检测按钮的方法。
以下是我的实施:
//At MapViewController
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if !annotation.isKind(of: Post.self) {
return nil
}
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "pin") as? MKPinAnnotationView
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin")
annotationView?.canShowCallout = true
annotationView?.animatesDrop = true
} else {
annotationView?.annotation = annotation
}
let postAnnotation = annotation as! Post
let calloutView = DetailCalloutView()
calloutView.titleLabel.text = ...
calloutView.timestampLabel.text = ...
calloutView.postContentTextView.text = ...
calloutView.profileImageView.image = ...
calloutView.deleteButton.addTarget(self, action: #selector(deleteButtonTap), for: .touchUpInside)
calloutView.chatButton.addTarget(self, action: #selector(chatButtonTap), for: .touchUpInside)
annotationView?.detailCalloutAccessoryView = calloutView
return annotationView
}
@objc func deleteButtonTap(_ sender: MKAnnotationView) {
let post = sender.annotation as? Post
let index = postArray.index(of: post) //Is there a way to implement something like this here??
...
}
@objc func chatButtonTap() {
print("123")
}
//At Post
class Post: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var post: String?
//All other properties
init(coordinate: CLLocationCoordinate2D, post: String, ...) {
self.coordinate = coordinate
self.post = post
...
}
}
//At DetailCallOutView
class DetailCalloutView: UIView {
let containerView: UIView = {
...
return v
}()
//All other UI elements
let chatButton: UIButton = {
let b = UIButton()
...
return b
}()
let deleteButton: UIButton = {
let b = UIButton()
...
return b
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
func setupViews() {
addSubview(containerView)
//adding subviews for all UI elements
containerView.addSubview(cButton)
containerView.addSubview(dButton)
//setting up constraints for all UI elements
}
}
我能够检测到聊天和删除按钮,但无法获得有关postArray或注释的帖子。有办法吗?
答案 0 :(得分:0)
第一个操作是添加到目标的类型,这里是UIButton
calloutView.deleteButton.tag = <#setToIndexOfArr#>
calloutView.deleteButton.addTarget(self, action: #selector(deleteButtonTap), for: .touchUpInside)
//
@objc func deleteButtonTap(_ sender: UIButton) {
let item = modelArr[sender.tag]
}