ios TableView 列表中的三态 UIButton

Three state UIButton in ios TableView List

我有 UITableView 中的学生出勤名单。每个单元格都有一个 UIButton 来设置学生出勤率,例如 PresentAbsentLeave 单击按钮。我怎样才能在一个按钮上实现这个。

单击按钮时更改按钮标题和背景颜色。就个人而言,我会使用三个不同的按钮,以便所有不同的选项同时可见。 UIPicker 也是一种选择。

UISegmentedControl 是您要找的东西吗?

请参阅 Apple 文档 here。它可以在故事板中配置为具有正确数量的片段和片段标题。当用户选择一个段时,它将突出显示,并取消选择任何其他段。

如果您的 tableViewCell 中有一个 UIButton,那么您的 UIButton 中有一个 UIButtoncellForRowAtIndexPath 中有 set button Tag with indexPath.row,例如-

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    attendanceListTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];

    cell.studentNameLbl.text=[NSString stringWithFormat:@"Student %ld",(long)indexPath.row];

    cell.editBtn.tag=indexPath.row;

    [cell.editBtn setTitle:[attandanceArry objectAtIndex:indexPath.row] forState:UIControlStateNormal];

    [cell.editBtn addTarget:self action:@selector(editAttendance:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}
-(void)editAttendance:(id)sender{

    UIButton *btn=(UIButton*)sender;

    if ([btn.titleLabel.text isEqualToString:@"P"]) {
        [btn setTitle:@"A" forState:UIControlStateNormal];
        [attandanceArry replaceObjectAtIndex:btn.tag withObject:@"A"];
    }else if ([btn.titleLabel.text isEqualToString:@"A"]) {
        [btn setTitle:@"L" forState:UIControlStateNormal];
        [attandanceArry replaceObjectAtIndex:btn.tag withObject:@"L"];
    }else if ([btn.titleLabel.text isEqualToString:@"L"]) {
        [btn setTitle:@"P" forState:UIControlStateNormal];
        [attandanceArry replaceObjectAtIndex:btn.tag withObject:@"P"];
    }

}

在这个attandanceArry中是mutableArray,所有默认值都是"P"capacity是你的number of studentseditBtn是你的单元格UIButton。在这里我使用 custom tableViewCell classattendanceListTableViewCell class 有 UIButton。最后,当你完成编辑考勤时,你可以使用 attandanceArry 作为结果数组。希望对您有所帮助...:)

您只需为 UITableViewCell 中的 UIButton 实施以下 @selector 即可。

- (void)btnSetMode:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    if (btn.tag == 0)
    {
        [btn setTitle:@"Present" forState:UIControlStateNormal];
        btn.tag = 1;
        // Define your required task...
    }
    else if (btn.tag == 1)
    {
        [btn setTitle:@"Absent" forState:UIControlStateNormal];
        btn.tag = 2;
        // Define your required task...
    }
    else if (btn.tag == 2)
    {
        [btn setTitle:@"Leave" forState:UIControlStateNormal];
        btn.tag = 3;
        // Define your required task...
    }
    else if (btn.tag == 3)
    {
        [btn setTitle:@"Attendance" forState:UIControlStateNormal];
        btn.tag = 0;
        // Define your required task...
    }
}

您只需按一下按钮即可完成所需的所有任务。