在tableview自定义按钮背景上添加图像

时间:2014-12-15 11:41:46

标签: ios objective-c uitableview

我想在tableview单元格上的按钮上添加图片,这是我的代码,一切正常但是在挑选图片后,它在imagebutton上未设置或可见,请帮帮我.... ..

cellForRowAtIndexpath方法

中的

  if(indexPath.row == 0)
    {
        cell.userInteractionEnabled = YES;
         cell.textLabel.text =@"Your Profile Photo";
         imageBtn = [[UIButton alloc]initWithFrame:CGRectMake(250, 5, 35, 35)];
           [imageBtn setBackgroundImage:[UIImage imageNamed:@"AFPFriendThumbnail.png"]    forState:UIControlStateNormal];
        [imageBtn addTarget:self
                     action:@selector(myAction)
           forControlEvents:UIControlEventTouchUpInside];

        imageView.backgroundColor = [UIColor lightGrayColor];

        [cell addSubview:imageBtn];

    }

按钮上的操作

-(void)myAction
{    
UIImagePickerController * picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentModalViewController:picker animated:YES];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
[imageBtn setImage:image forState:UIControlStateSelected];
imageBtn.backgroundColor = [UIColor redColor];
[tableView_ reloadData];
}

3 个答案:

答案 0 :(得分:6)

尝试使用UIControlStateNormal

[imageBtn setImage:image forState: UIControlStateNormal];

但我可以看到你在设置图片后重新加载tableView,这将取代imageBtn

 imageBtn = [[UIButton alloc]initWithFrame:CGRectMake(250, 5, 35, 35)]; // Creating a button every time.

它应该无需重新加载,因为您保留对imageBtn的引用,以便您可以直接设置。请尝试删除[tableView_ reloadData]

答案 1 :(得分:2)

你应该永远在cellForRowAtIndexPath中调用reloadData或任何单元重载方法。这将导致无限递归崩溃。

此外,如果要求将单元格出列并且返回nil,则只应向表格视图单元格添加视图。

相反,当你从dequeue方法得到nil时,添加你的按钮并用唯一标签设置它。如果您返回一个回收的单元格,请使用viewWithTag获取该按钮,并根据需要更改图像和操作。 (您需要删除之前的操作,因为按钮可以附加多个操作。)

答案 2 :(得分:1)

替换

         imageBtn = [[UIButton alloc]initWithFrame:CGRectMake(250, 5, 35, 35)];

有了这个

         imageBtn = [[UIButton [UIButton buttonWithType:UIButtonTypeCustom];
         imageBtn.frame=CGRectMake(250, 5, 35, 35);

并且。 。 取代

        [imageBtn setImage:image forState:UIControlStateSelected];

有了这个..

        [imageBtn setImage:image forState: UIControlStateNormal];

我希望这对你有帮助..