我正在将我的应用程序从目标C转换为Swift的过程。除此之外,我在所有领域都表现良好。在我的目标C文件中,我有一个允许多个选择的UitableView。当用户选择一个单元格时,该对象的信息存储在数组中。当用户再次单击单元格时,该对象被删除。我试图弄清楚在Swift 3中的工作方式,我可以添加对象,但是我似乎无法弄清楚如何从数组中删除该对象。请指教。以下是我试图转换的目标C的代码。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
RibbonsInfo *ribbonsInfo = [ribbonsArray objectAtIndex:indexPath.row];
UITableViewCell *cell = [ribbonTableView cellForRowAtIndexPath:indexPath];
if (ribbonTableView.allowsMultipleSelection == YES) {
if(cell.accessoryType == UITableViewCellAccessoryNone) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[selectedRibbons addObject:ribbonsInfo];
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
[selectedRibbons removeObject:ribbonsInfo];
}
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
使用Swift,您只能使用其index
从Array
中删除项目。因此,您需要在该数组中获取该对象的索引,然后致电selectedRibbons.remove(at: index)
。
例如。
var array = Array<String>()
array.append("apple")
array.append("banana")
array.append("orange")
print(array) // ["apple", "banana", "orange"]
if let index = array.index(of: "banana") {
array.remove(at: index)
}
print(array) // ["apple", "orange"]