如何在目标c

时间:2017-01-30 06:42:01

标签: ios objective-c uitableview

我是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];
}

我正在获得这样的输出

enter image description here

的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;
}

我的问题是我在文本框中只得到一个值。我需要在文本框中获取所有选定的值。这该怎么做?在此先感谢!

3 个答案:

答案 0 :(得分:3)

获取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];
}

答案 1 :(得分:2)

尝试这个,不直接存储到数组中,您可以根据您的选择附加字符串。我希望这对你有用。

[txtactivity setText:[[txtactivity text] stringByAppendingString:[NSString stringWithFormat:@", %@", [activityarray objectAtIndex:indexPath.row]]]];

答案 2 :(得分:0)

我希望txtactivity是你的文本域。在您的代码中,您只是将文本字段文本设置为选定的值。它将替换当前文本。而不是将所选值附加到文本字段内容。 更改代码

txtactivity.text=[NSString stringWithFormat:@"%@",[activityarray objectAtIndex:indexPath.row]];

到这个

txtactivity.text=[NSString stringWithFormat:@"%@,%@",txtactivity.text,[activityarray objectAtIndex:indexPath.row]]

这会将新选择的值附加到textfield的内容中。