Swift cannot assign subtitle in MKAnnotation

2019-08-11 22:38发布

I'm attempting to programmatically update the subtitle within MKAnnotation. The following lines of code produce a cannot assign subtitle in annotation error:

let annotation: MKAnnotation = mapView.annotations[0] as! MKAnnotation
annotation.subtitle = nil

Could anyone help lead me in a direction where I can update the subtitle after the MKAnnotation is shown within the map?

1条回答
够拽才男人
2楼-- · 2019-08-11 23:27

MKAnnotation is a protocol. In that protocol, subtitle is read-only. That means it cannot be set.

So, because you have cast this annotation to an MKAnnotation, you cannot set the subtitle.

If you know know what class the annotation really is, then you can cast to that class, and presumably it will have a subtitle which is read/write so you can set it. For example, it might be an MKPointAnnotation, or you might have your own custom annotation class. Then you'll be able to cast to that, and now you can set the subtitle.

查看更多
登录 后发表回答