ios - 从另一个 ViewController 访问数组并对其进行排序

标签 ios swift delegates protocols

假设我有一个包含一些值的数组:

let countryName = ["USA", "Canada", "Italy", "Israel"]

当点击按钮时,它开始按区域对该数组进行排序:

let countryToRegionDic = [
    "United States" : "America",
    "Czech Republic" : "Europe",
]

func useFilter() {
    self.countryName.forEach({ (country) in

        let countryRegion = self.countryToRegionDic[country]

        if (countryRegion != nil && europeFilter.contains(countryRegion!)){

            self.filtered.append(country)
            self.countryName = self.filtered.removeDuplicates()
            self.tableView.reloadData()
        }           
    })
}

我希望它在另一个“FiltersViewController”中使用这个排序功能,因为我从这个“FiltersViewController”获得过滤值。认为我需要使用委托(delegate)或协议(protocol),但不知道如何以及在哪里。谢谢!

最佳答案

关于委托(delegate)模式的一个小例子...

public protocol CountrySort: class
{
    func sorted(_ array: [String]) -> Void
}

public class ControllerA
{
    public var countryName: [String]!

    public weak var delegate: CountrySort?

    public func userFilter() -> Void
    {
        // Do something here...
        countryName.sort()

        self.delegate?.sorted(countryName)
    }
}

public class ControllerB
{
    public init()
    {
        // Call the other UIViewController
        let controllerA: ControllerA = ControllerA()
        controllerA.countryName = ["USA", "Canada", "Italy", "Israel"]

    }
}

extension ControllerB: CountrySort
{
    public func sorted(_ array: [String]) -> Void
    {
        print("And now the other controller sort the array")

        for item in array
        {
            print("\t\(item)")
        }
    }
}

关于ios - 从另一个 ViewController 访问数组并对其进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42139726/

相关文章:

android - 将带有解析的推送发送到特定设备?

ios - 从 iPhone SDK 中的视频 url 创建缩略图

ios - UIAlertAction 按钮文本左对齐

iphone - XCode (iOS) 中委托(delegate)的自动导入回调

vb.net - Action 委托(delegate) c# 到 vb.net 的转换

ios - 背景渐变在横向模式下看不正确

ios - AVCaptureSession如何使静音输入音频设备?

swift - iOS 11 simd 矩阵线性组合去哪儿了?

ios - 方法调配不起作用

delegates - 为什么使用委托(delegate)和协议(protocol)而不是仅仅在 Swift 中传递一个实例?