一个按钮添加到TableView中单元格:

问题描述:

我有一个UI的tableView,我想创建在Safari设置用于清除历史记录的一个按钮:一个按钮添加到TableView中单元格:

enter image description here

的代码我已经试过没有真正的工作,我敢肯定有一个更好的方法:

 case(2): 
      // cell = [[[ButtonLikeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 


      if (indexPath.row == 0) 
      {    
       UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
       [button setFrame:cell.bounds]; 
       [button addTarget:self action:@selector(clearButtonClick) forControlEvents:UIControlEventTouchUpInside]; 
       [button setBackgroundColor:[UIColor purpleColor]]; 
       [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 
       [button setTitle:@"Clear Data" forState:UIControlStateNormal]; 
       cell.accessoryView = nil; 
       cell.clipsToBounds=YES; 
       [cell.contentView addSubview:button]; 
      } 

      break; 
    } 
} 

return(cell); 

}

上的tableview细胞的子类是矫枉过正这一点,基本上所有你需要做的是设置为textLabel的文本对齐到中心

case(2): 
     if (indexPath.row == 0) 
     { 
      cell.textLabel.textAlignment = UITextAlignmentCenter; 
     } 
     break; 
+0

你是对的!我在印象textLabel通过sizeToFit,所以改变对齐将无法正常工作。 – 2012-01-31 09:53:21

没有必要用一个实际的UIButton。

行和“正常”行之间的唯一区别是标签的位置。 子类的UITableViewCell和覆盖-laysubviews居中标签就大功告成了,就像这样:

@interface ButtonLikeCell : UITableViewCell 

@end 

@implementation ButtonLikeCell 

-(void)layoutSubviews 
{ 
    self.titleLabel.center = self.center; 
} 

@end 

这将重新定位电池的标签,使它看起来类似于你在找什么。

+0

你可以扩大一点貉子?这是我在IOs – JonWells 2012-01-30 16:06:26

+0

的第几天,这不是一个uitableviewcell内的按钮,它只是一个uitableviewcell,textLabel的textAlignment属性设置为UITextAlignmentCenter – wattson12 2012-01-30 16:09:27

+0

@CrimsonChin我更新了我的答案。 – 2012-01-30 16:12:43