(Swift HomeKit)应用程序需要两次刷新视图控制器才能反映附件值的变化

时间:2016-10-13 14:29:35

标签: ios swift homekit

我正在编写一个控制家庭套件配件(灯泡)的应用程序,除了在我的视图控制器中,当我更新说明特征的布尔开/关状态时,我需要两次迭代来回转换。查看控制器以反映更改后的值。

这可能是代表的问题吗?我不知道该怎么办。

我有一个配件视图UISwitch用于控制灯泡电源状态的每个表格单元格,我在顶部的工具栏上有一个UISwitch,可以打开或关闭所有灯光。

这是我的cellForRowAtIndexPath方法,其中powercharacteristic是所有灯泡的电源状态特征的数组,

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // Configure the cell...
    let cellIdentifier = "DeviceTableViewCell"
    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! DeviceTableViewCell
    cell.deviceName.text = devices[indexPath.row].name



    //creating the switch
    let deviceSwitch = UISwitch(frame: CGRect.zero) as UISwitch

    //init the switch
    updateValues()
    let isOn = powerCharacteristic[(indexPath as NSIndexPath).row].value as! Bool
    deviceSwitch.setOn(isOn, animated: true)

    //letting switch know what cell called it
    deviceSwitch.tag = (indexPath as NSIndexPath).row

    //adding selector
    deviceSwitch.addTarget(self, action: #selector(changeStatusFromButton), for: .valueChanged)

    //adding cell in table
    cell.accessoryView = deviceSwitch

    //on Off Label
    if isOn {
        cell.isOnOrOff.text = "On"
    } else {
        cell.isOnOrOff.text = "Off"
    }


    return cell
}

这一部分有效。但是当我在顶部翻转开关时,

@IBAction func mainSwitchToggled(_ sender: AnyObject) {
    writeAllValue()

}

调用

func writeAllValue() {
    for characteristic in powerCharacteristic{

        characteristic.writeValue(mainSwitch.isOn, completionHandler: {(error) in
            if error != nil {
                print("Something went wrong with writing all value")
            } else {
                print("Writing all Value Successful")
            }})

    }
    tableView.reloadData()



}

它开始循环,最后根据开关的状态开启或关闭它们。

0 个答案:

没有答案