【问题标题】:Change background color of the button in UITableViewCell based on selection根据选择更改 UITableViewCell 中按钮的背景颜色
【发布时间】:2013-03-12 18:47:51
【问题描述】:

我有一个 UITableView。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//Where we configure the cell in each row

static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell;

cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}


self.myButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.myButton.tag = 5;
self.myButton.frame = CGRectMake(190.0f, 5.0f, 70.0f, 25.0f);
self.myButton.layer.borderColor = [UIColor blackColor].CGColor;
self.myButton.layer.borderWidth = 0.5f;
self.myButton.backgroundColor = [UIColor grayColor];
[self.myButton setTitle:@"Set Active" forState:UIControlStateNormal];
[self.myButton addTarget:self action:@selector(myButton:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview: self.myButton];

cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

}

-(void) myButton:(id)sender{
[sender setBackgroundColor:[UIColor redColor]];
}

假设,tableview 部分中有 3 行。我有 3 行的按钮。 在第一种情况下,第一行的按钮应该是红色的,其他两行应该是灰色的。 如果我选择第二行的按钮,那么第二行的按钮应该是红色的,另外 2 个是灰色的,以此类推。我还没有想出办法来做到这一点。有什么建议吗?

我可以更改从单元格中选择的按钮的颜色。但在同一实例中,先前选择的按钮和所有其他按钮(选定按钮除外)应为默认颜色。一次只会突出显示一个按钮,并且该按钮始终是该实例的选定按钮。

【问题讨论】:

    标签: iphone ios uitableview uibutton


    【解决方案1】:

    我认为这样做的正确方法 - 子类 UITableViewCell 并声明自己的协议,该协议将通知委托在哪个单元格按钮被按下,并在委托中 - 循环遍历所有单元格并为所有单元格设置默认颜色并为选择。 我发了demo project

    【讨论】:

      【解决方案2】:

      简单的方法是为每个按钮设置不同的标签。像这样:

      button.tag = indexPath.row + c;
      

      当 'c' 为常数时。 在你的方法中:

      -(void) myButton:(id)sender{
           for( int i=0; i<numberOfRowsInTable; ++i )
              [(UIButton *)[self.view viewForTag:i+c] setBackgroundColor:[UIColor grayColor]];
           [(UIButton *)sender setBackgroundColor:[UIColor redColor]];
      }
      

      但如果您在表格中有 2 个或更多部分,这种方式可能行不通

      【讨论】:

      • 我的问题是如何将未选中的按钮设置为默认颜色。只有选中的按钮应该是红色的。
      【解决方案3】:

      看看这个:How can I loop through UITableView's cells?

      遍历单元格并将“非活动”按钮设置为灰色。

      【讨论】:

        【解决方案4】:

        试试这个代码:

        -(void) myButton:(id)sender{
            NSLog(@"sender Tag=== %d",[sender tag]);
            UIButton *btn=(UIButton *)sender;
            [btn setBackgroundColor:[UIColor redColor ]];
        
        }
        

        【讨论】:

        • 我的问题是如何将未选中的按钮设置为默认颜色。只有选中的按钮应该是红色的。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-30
        • 1970-01-01
        • 2018-10-01
        • 2015-11-01
        • 1970-01-01
        • 2014-02-10
        • 1970-01-01
        相关资源
        最近更新 更多