我的项目是一个有很多的注解点地图,用户可以查找特定的注释得益于pickerView。除了所有注释点的名单似乎随机显示所有的罚款。我想注释按字母顺序排序。
这里是我当前工作的代码:
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return self.mapView.annotations[row].title ?? "No title"
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.mapView.selectAnnotation(self.mapView.annotations[row], animated: true)
}
我已经尽力实现这一点,但没有成功...
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
let sortedNames = self.mapView.annotations.sorted(by: {$0.title < $1.title})
return sortedNames[row].title ?? "No title"
}
我已经得到了这个错误:
无法将类型的价值“字符串?”预期参数类型“UIContentSizeCategory”
任何暗示将不胜感激。
我知道这个问题是有点老了回答,但对于其他人遇到的问题,问题是该字符串不能是可选的。修复它要么提供展开它的默认值或力。例如,这将是一个解决问题的办法:
let sortedNames = self.mapView.annotations.sorted(by: { ($0.title ?? "") < ($1.title ?? "") }))
return sortedNames[row].title ?? "No title"
试图排序的字符串属性不同类的数组时,我刚刚正是这种错误。这个问题似乎是要排序由属性是可选的。使用非可选属性按预期工作,使用可选属性给出了几分怪异“UIContentSizeCategory”的错误。
这样的事情应该做您的需要:
let sorted = self.mapView.annotations { (a1, a2) -> Bool in
if let s1 = a1.title {
if let s2 = a2.title {
return s1 > s2
}
}
return false
}