4

我正在以编程方式创建按钮,然后我想添加功能,当它们被点击/按下时,它们会保持突出显示,除非再次点击。我现在正在做的是创建按钮,然后尝试添加 IBAction。但是,问题是我在一个方法中创建了按钮,然后我不确定如何在我的 IBAction 中引用该按钮。这是我的代码:

UIButton* testButn = [UIButton buttonWithType:UIButtonTypeCustom];
  [testButn setFrame:CGRectMake(0, 135, 40, 38)];
  [testButn setImage:[UIImage imageNamed:@"test_butn_un.png"] forState:UIControlStateNormal];
  [testButn setImage:[UIImage imageNamed:@"test_butn_pressed.png"]   forState:UIControlStateHighlighted];
[testButn addTarget:self action:@selector(staypressed:) forControlEvents:UIControlEventTouchUpInside];
[self.contentview addSubview:testButn

-(IBAction)staypressed:(id)sender{

//Not sure what to do here, since this method doesn't recognize testButn, How do I reference testButn
4

3 回答 3

9

发件人是 testButn。您应该将 stayPressed 的参数类型从 (id) 更改为 (UIButton *)

除非一个操作方法连接到几个不同的对象类,否则最好将 id 替换为您正在使用的任何对象类。如果您在 IB 中连接事物,这将很有用,因为它不会让您将它连接到错误类型的对象。

它不起作用的事实并不是因为它不识别您的按钮。你的方法是错误的。我认为您需要连接一个动作才能触地,并且可能将选定状态设置为“是”。在您的按钮定义中,您需要为所选状态设置一个 imageForState:。按照您现在的操作方式,直到修改后才会调用该方法。

像这样的东西:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIButton* testButn = [UIButton buttonWithType:UIButtonTypeCustom];
    [testButn setFrame:CGRectMake(0, 135, 40, 38)];
    [testButn setImage:[UIImage imageNamed:@"New_PICT0019.jpg"] forState:UIControlStateNormal];
    [testButn setImage:[UIImage imageNamed:@"New_PICT0002.jpg"]   forState:UIControlStateSelected];
    [testButn addTarget:self action:@selector(stayPressed:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:testButn];
}

-(void)stayPressed:(UIButton *) sender {
    if (sender.selected == YES) {
        sender.selected = NO;
    }else{
        sender.selected = YES;
    }
}
于 2013-01-31T16:22:10.393 回答
2

您需要将发件人转换为 UIButton。

- (IBAction)staypressed:(id)sender
{
    UIButton *theButton = (UIButton*)sender;

    //do something to theButton
}
于 2013-01-31T16:22:00.690 回答
2
UIButton* testButn = [UIButton buttonWithType:UIButtonTypeCustom];
  [testButn setFrame:CGRectMake(0, 135, 40, 38)];
  [testButn setImage:[UIImage imageNamed:@"test_butn_un.png"] forState:UIControlStateNormal];
  [testButn setImage:[UIImage imageNamed:@"test_butn_pressed.png"]   forState:UIControlStateHighlighted];
  [testButn addTarget:self action:@selector(staypressed:) forControlEvents:UIControlEventTouchUpInside];
  testButn.tag = 1;
  [self.contentview addSubview:testButn

-(IBAction)staypressed:(id)sender
 {
     if ([sender tag]==1)
     {
         somecodes...
     }
 }
于 2013-01-31T16:55:49.513 回答