添加图像后,UIButtonTypeCustom不再有效

时间:2012-11-12 13:34:22

标签: ios uibutton uiimage

我有一个里面有图像的按钮,当我按下按钮时我想要一个弹出窗口。当按钮为空时,内部没有图像,一切正常,我现在已添加图像,按钮不再有效。 Button对应于IBAction,并通过IBOutlet连接到XIB。我该怎么办?

 - (void)viewDidLoad
 {      
      //.....
      self.myButton = [UIButton buttonWithType:UIButtonTypeCustom];

     if(UI_USER_INTERFACE_IDIOM()== UIUserInterfaceIdiomPhone){

        self.myButton.frame = CGRectMake(160, 502, 73, 33);
       [self.myButton setImage:[UIImage imageNamed:@"iphone_legenda.png"] 
                                           forState:UIControlStateNormal];
        self.myButton.contentMode = UIViewContentModeScaleToFill;

     }else{

       self.myButton.frame = CGRectMake(330, 917, 182, 68);
       [self.myButton setImage:[UIImage imageNamed:@"ipad_legenda.png"] 
                                         forState:UIControlStateNormal];
       self.myButton.contentMode = UIViewContentModeScaleToFill;
     }


 [self.view addSubview:self.myButton]; 
 /*The problem arose in this line, without addSubview the image  you could not see 
  but the button worked, added addSuview the image you see but the button does not 
  work anymore*/

  NSLog(@"The button is %@", self.myButton);

 /*The button is <UIButton: 0x80f1e90; frame = (330 917; 182 68); opaque = NO; 
  layer = <CALayer: 0x80f1210>>*/

     //.......

 }

 -(IBAction)pressedButton:(id)sender{
      //This method initially worked
 }

1 个答案:

答案 0 :(得分:1)

如果已在XIB中定义了该按钮,则代码将创建另一个不带任何事件(IBAction)的不同按钮。

您可以将代码更改为:

- (void)viewDidLoad
{      
  //.....

 if(UI_USER_INTERFACE_IDIOM()== UIUserInterfaceIdiomPhone){

    self.myButton.frame = CGRectMake(160, 502, 73, 33);
   [self.myButton setImage:[UIImage imageNamed:@"iphone_legenda.png"] 
                                       forState:UIControlStateNormal];
    self.myButton.contentMode = UIViewContentModeScaleToFill;

 }else{

   self.myButton.frame = CGRectMake(330, 917, 182, 68);
   [self.myButton setImage:[UIImage imageNamed:@"ipad_legenda.png"] 
                                     forState:UIControlStateNormal];
   self.myButton.contentMode = UIViewContentModeScaleToFill;
 }

}

其他选择是有两个XIB。一个用于iPad,另一个用于iPhone。