如何在表格视图中选择默认国家/地区?

时间:2019-01-29 04:14:29

标签: ios swift uitableview

我构建了一个需要电话验证的应用。单击按钮可以更改国家代码。默认情况下,所选国家/地区必须是带有“ 60”的国家/地区(例如)。它应该像这样工作:单击按钮-显示国家/地区列表,默认国家/地区应带有选中标记。然后,如果我单击另一个国家,如果我单击按钮,则最新选择的国家应带有复选标记。但是发生的是,当callingCode =“ 60”(默认情况下)时,它之后的代码无法通过(让i = ..)。仅当callingCode = vc.country.calling_code时,该代码(让i = ..)才能通过。有谁知道最好的方法是什么?

func selectDefaultCountry(countries: [Countries]) {
    var callingCode = ""

    if vc.country.calling_code != ""  {
        callingCode = vc.country.calling_code
    }
    else {
        callingCode = "60"
    }

    if let i = countries.firstIndex(where: {$0.calling_code == callingCode}) {

        let indexPath = IndexPath(row: i, section: 0)

        vc.changeCountryTV.selectRow(at: indexPath, animated: true, scrollPosition: .none)
        // Green checkmark
        vc.changeCountryTV.cellForRow(at: indexPath)?.accessoryType = .checkmark
        vc.changeCountryTV.cellForRow(at: indexPath)?.tintColor = Constants.Colors.greenColor
    }
}

2 个答案:

答案 0 :(得分:0)

为此,您需要使用cellForRowAt indexPath方法比较选定的国家/地区:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // Your code for initialize UITableView cell
    let country = countries[indexPath.row]
    if(vc.country.calling_code == country.calling_code)
        cell.accessoryType = .checkmark
    else
        cell.accessoryType = .none
    }

答案 1 :(得分:0)

以以下方式创建国家对象

struct CountryModel:Decodable{
    var countries:[Country]?
}

struct Country:Decodable {
    var name:String?
    var isSelected:Bool?
}

在您的SelectDefaultCountry函数中,将isSelected设置为True,如果用户尝试通过单击国家/地区按钮进行更改,则将Firstly all isSelected更改为false并为选定的一项设置为true。这应该使您更易于管理。