UIButton在cellForRowAtIndexPath中返回为(null)

时间:2015-10-12 10:49:32

标签: ios objective-c uibutton

我在UI按钮上遇到了一些问题,它可以点击前两行。但不是第3个,所以我尝试记录按钮,当首次加载视图时它返回为null。

以下是我在cellForRowAtIndexPath

中创建按钮的方法
UIButton *Button = (UIButton *)[cell viewWithTag:4];
    [Button addTarget:self action:@selector(Button:) forControlEvents:UIControlEventTouchUpInside];
    NSLog(@"BUTTON: %@",Button);

这是我在日志中得到的

 BUTTON: (null)

3 个答案:

答案 0 :(得分:0)

你需要这样做..

UIButton *createbtn=[UIButton buttonWithType:UIButtonTypeSystem];

createbtn.frame=CGRectMake(200, 20, 100, 30);

[createbtn setTitle:@"Click" forState:UIControlStateNormal];

[createbtn addTarget:self action
                        :@selector(onButtonClk:) forControlEvents:UIControlEventTouchUpInside];

[cell addSubview:createbtn];

return cell;  

答案 1 :(得分:0)

按照以下步骤

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *stringIdentifier = @"CellIdentifier";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:stringIdentifier];
  if(cell==nil)
  {
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:stringIdentifier];
  }
 //1. create button type as custom
 UIButton *Btn=[UIButton buttonWithType:UIButtonTypeCustom];

 //2. set the frame for visibility
 Btn setFrame:CGRectMake(10,5,55,55)]; // change the frame where you need

 //3. add the action for button
 [Btn addTarget:self action:@selector(actionButtonPress:) forControlEvents:UIControlEventTouchUpInside];

 //4. get the current cell index
 Btn.tag = indexpath.row;

 //5. choices if you want to add image for button
 [Btn setBackgroundImage:[UIImage imageNamed:@"yourImageName.png"] forState:UIControlStateNormal];

 //6. if you want to add title for button
 [Btn setTitle:@"Add" forState:UIControlStateNormal];

 //7.set font for title
 [Btn.titleLabel setFont:[UIFont systemFontOfSize:15]];

 //8. set color for title
 [Btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

//9. add subview to cell
 cell.contentView addSubview:Btn];

 return cell;

}

按钮操作方法

-(void)actionButtonPress:(UIButton*)sender
{
   //get the current index 
   NSLog(@"current index == %@", sender.tag);
   // do your stuff here
}

你也可以在下面的cellForRowAtIndexPath中设置按钮的标签,如下所示

   UIButton *Btn = (UIButton*)[cell.contentView viewWithTag:4];
   Btn.tag = indexpath.row;

积分转到我可爱的兄弟AnbuKarthickeyan

答案 2 :(得分:0)

所有变量命名约定的第一个都已关闭。您应将Button命名为button

第二次,我建议您创建一个自定义单元格 - UITableViewCell的子类和- (id)initWithStyle:(UITableViewCellStyle)iStyle reuseIdentifier:(NSString *)iReuseIdentifier方法中的按钮。

cellForRowAtIndexPath:中创建按钮或更改按钮是一项繁重的工作,因为每个单元格绘制和重新绘制都会调用此方法。

第三次,在自定义单元格类中实现- (void)layoutSubviews方法,以便在单元格中进行任何运行时更改。