0

我有一个带有图像的按钮,当我按下按钮时,我想弹出一个窗口。当按钮为空,内部没有图像时,一切正常,我现在添加了图像,按钮不再起作用。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
 }
4

1 回答 1

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。

于 2012-11-12T15:21:04.193 回答