[英]How to add multiselect UITableView value to UITextField in objective c
我是iOS的新手,現在面臨將多重選擇表值添加到文本字段的問題。 我的代碼在DidSelectRowAtIndexPath中是這樣的
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
txtactivity.text=[activityarray objectAtIndex:indexPath.row];
lblactivity.text=[NSString stringWithFormat:@"%@",[idActivityarray objectAtIndex:indexPath.row]];
txtactivity.text=[NSString stringWithFormat:@"%@",[activityarray objectAtIndex:indexPath.row]];
[[tableactivity cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryCheckmark];
}
我正在得到這樣的輸出
CellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text=[NSString stringWithFormat:@"%@",[activityarray objectAtIndex:indexPath.row]];
return cell;
}
我的問題是我在文本框中僅獲得一個值。 我需要在文本框中獲取所有選定的值。 這個怎么做? 提前致謝!
采取NSMutableArray並將其初始化為viewDidLoad
。 然后使用以下代碼。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(!arrSelectedValue containsObject:[activityarray objectAtIndex:indexPath.row]){
[arrSelectedValue addObject:[activityarray objectAtIndex:indexPath.row]];
txtactivity.text = [arrSelectedValue componentsJoinedByString:@","];
}
[[tableactivity cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryCheckmark];
}
- (void)tableView:(UITableView *)tableView didDeSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(arrSelectedValue containsObject:[activityarray objectAtIndex:indexPath.row]){
[arrSelectedValue removeObject:[activityarray objectAtIndex:indexPath.row]];
txtactivity.text = [arrSelectedValue componentsJoinedByString:@","];
}
[[tableactivity cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryNone];
}
試試這個,不直接存儲到數組中,您可以根據選擇附加字符串。 希望這對您有用。
[txtactivity setText:[[txtactivity text] stringByAppendingString:[NSString stringWithFormat:@", %@", [activityarray objectAtIndex:indexPath.row]]]];
我希望txtactivity是您的文本字段。 在您的代碼中,您只是將文本字段文本設置為選定值,它將替換當前文本。 取而代之的是將選定的值附加到文本字段內容中。 更改密碼
txtactivity.text=[NSString stringWithFormat:@"%@",[activityarray objectAtIndex:indexPath.row]];
對此
txtactivity.text=[NSString stringWithFormat:@"%@,%@",txtactivity.text,[activityarray objectAtIndex:indexPath.row]]
這會將新選擇的值附加到文本字段的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.