我想展示两个关于未连接和已连接的部分
我的速度不是很好。
这是我的代码
https://www.codepile.net/pile/vNYKLZ6L
当我运行它时,它在这里崩溃let peripheral = self.peripherals[indexPath.row]
致命错误:索引超出范围
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上,而connectPeripherals
在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
}