有没有办法在UIButtton本地采取行动?

时间:2014-03-05 20:54:45

标签: ios objective-c uibutton scope

我正在设置一个表格,其中包含以下代码:

UIButton *done = [[UIButton alloc]initWithFrame:CGRectMake(20, 25, 40, 40)];
[done setImage:[UIImage imageNamed:@"unchecked.png"] forState:UIControlStateNormal];
[done addTarget:self action:@selector(done:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:done];
return cell;

这不起作用因为此按钮仅在此范围内声明,我只想在此次点击中更改其图像

3 个答案:

答案 0 :(得分:1)

使用done:方法更改图片。

- (void)done:(id)sender
{
    UIButton *button = (UIButton *)sender;

    [button setImage:[UIImage imageNamed:@"yourImage.png"] 
            forState:UIControlStateNormal];
}

答案 1 :(得分:0)

你做的方法是什么样的? 我认为如果你向方法添加sender参数,你可以访问该按钮。

- (void)done:(id)sender
{
    UIButton *button = (UIButton*)sender;
    [button doStuff]; 
}

答案 2 :(得分:0)

您必须申报ivar或私人/公共财产。因此,您可以从任何地方更改其图像,例如:

@interface ViewController ()

@property UIButton *done;

@end


@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.done = [[UIButton alloc]initWithFrame:CGRectMake(20, 25, 40, 40)];
    [self.done setImage:[UIImage imageNamed:@"unchecked.png"] forState:UIControlStateNormal];
    [self.done addTarget:self action:@selector(done:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.done];
}

- (void)done:(UIButton *)sender
{
    //Do something.. like change image

    [self.done setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];
}

@end

或者您将发件人声明为UIButton,如下所示:

- (void)done:(id)sender
{
    UIButton *done = (UIButton *)sender;

    //Do something with the button
}