我需要添加TableView
,我應該可以點擊tableview
中的幾個項目並將其保存到NSMutable dictionary
或其他合適的項目。從tableview中選擇多個項目 - 初學者
我知道你必須爲此使用NSMutable Dictionary
。但我不明白如何做到這一點。
有人可以請指出一個很好的教程或爲我提供一些示例代碼。
我需要添加TableView
,我應該可以點擊tableview
中的幾個項目並將其保存到NSMutable dictionary
或其他合適的項目。從tableview中選擇多個項目 - 初學者
我知道你必須爲此使用NSMutable Dictionary
。但我不明白如何做到這一點。
有人可以請指出一個很好的教程或爲我提供一些示例代碼。
您將不得不爲此使用委託方法。
首先確保你的表視圖設置好(delegate和datasource),然後
執行委託的:
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
。
您訪問選定的行索引:[indexPath row]
。
然後你可以存儲這個值。
這是Matt Gallagher在Cocoa With Love的一篇文章,您可能會發現照明。
有點過時,但原則是一樣的。
您可以在此方法中使用NSMutableDictionary
爲:
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSMutableDictionary *dict = [NSMutableDictionary alloc] init];
[dict setObject:[NSString stringWithFormat:"%@", cell.Label.text] forKey:[NSString stringWithFormat:"Key%d", indexPath.row]];
}
這真的取決於你的數據模型。首先你需要一個NSMutableArray而不是一個NSMutableDictionary;
//declare an NSMutableArray in the interface
@interface Class : SuperClass {
NSMutableArray *_arrayWithMySelectedItems;
}
//in one of your init/preparation methods alloc and initialize your mutable array;
- (void)viewDidLoad {
[super viewDidLoad];
_arrayWithMySelectedItems = [NSMutableArray alloc] init];
}
//now before you forget it add release in your dealloc method
- (void)dealloc {
[_arrayWithMySelectedItems release];
[super dealloc];
}
//add this following code to your didSelect Method part of tableView's delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//if you have only one category, you will probably have something like this
[_arrayWithMySelectItems addObject:[dataModelArray objectAtIndex:indexPath.row];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
聲明的tableview的didselect行內的字符串然後給該字符串= [您的填充陣列objectAtIndex:indexpath.row];然後根據您的意願將其添加到字典或nsmutable數組中。