我想展示关于未连接和已连接的两个部分 我的 swift 不是很好。
这是我的代码 https://www.codepile.net/pile/vNYKLZ6L
当我运行它时,它会在这里崩溃
let peripheral = self.peripherals[indexPath.row]
fatal error: Index out of range
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//Connect to device where the peripheral is connected
let cell = tableView.dequeueReusableCell(withIdentifier: "BlueCell") as! PeripheralTableViewCell
let peripheral = self.peripherals[indexPath.row]
//let RSSI = self.RSSIs[indexPath.row]
if indexPath.section == 0 {
if peripheral.name == nil {
cell.peripheralLabel?.text = "nil"
} else {
cell.peripheralLabel?.text = peripheral.name
}
} else {
if connectPeripherals.count == 0 {
cell.peripheralLabel?.text = "nil"
} else {
cell.peripheralLabel?.text = self.connectPeripherals[indexPath.row].name
}
}
//cell.rssiLabel.text = "RSSI: \(RSSI)"
print("tableview連線有\(connectPeripherals.count)個")
print("tableview未連線有\(peripherals.count)個")
return cell
}
这里是 numberOfRowsInSection 函数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0{
return self.peripherals.count
} else {
return self.connectPeripherals.count
}
}
最佳答案
据我所知,peripherals
在 section_0 上,connect Peripherals
在 section_1 上,因此您可以这样重新组织代码:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BlueCell") as! PeripheralTableViewCell
if indexPath.section == 0 {
let peripheral = self.peripherals[indexPath.row]
cell.peripheralLabel?.text = peripheral.name != nil ? peripheral.name : "nil"
} else {
let connectedPeripheral = self.connectPeripherals[indexPath.row]
cell.peripheralLabel?.text = connectedPeripheral.name != nil ? connectedPeripheral.name : "nil"
}
print("tableview連線有\(connectPeripherals.count)個")
print("tableview未連線有\(peripherals.count)個")
return cell
}
关于ios ble 在 Swift fatal error : Index out of range 中使用 tableview 连接多个设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48364626/