swift - 如何按字母顺序排列注释数组

时间:2018-01-30 23:15:21

标签: swift annotations mapkit mkannotation

我的项目是一个包含大量注释点的地图,用户可以通过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"

    }

我有这个错误:

  

无法转换'String ??'类型的值预期的参数类型   'UIContentSizeCategory'

任何提示都将不胜感激。

2 个答案:

答案 0 :(得分:1)

我知道这个问题回答有点老了,但是对于其他有问题的人来说,问题是String不能是可选的。修复它以提供默认值或强制解开它。例如,这将是该问题的一种解决方案:

let sortedNames = self.mapView.annotations.sorted(by: { ($0.title ?? "") < ($1.title ?? "") }))
return sortedNames[row].title ?? "No title"

答案 1 :(得分:0)

当我尝试通过字符串属性对另一个类的数组进行排序时,我刚遇到了这个错误。问题似乎是您排序依据的属性是可选的。使用非可选属性可以按预期方式工作,使用可选属性会产生一些奇怪的“ 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
        }
相关问题