【问题标题】:Change UIImage when UIButton is pressed按下 UIButton 时更改 UIImage
【发布时间】:2014-10-10 08:14:30
【问题描述】:

当我按下 UIButton 时,它会改变我的 UIImage,而当我释放它时,它会保持这种状态。我想要做的是当 UIButton 被释放回到我原来的 UIImage

这是代码:

文件.h

@property (strong, nonatomic) IBOutlet UIImageView *Character;
@property (strong, nonatomic) IBOutlet UIButton *TapGreen;
-(IBAction)TapGreen:(id)sender;

文件.m

-(IBAction)TapGreen:(id)sender{
_Character.image = [UIImage imageNamed:@"CharacterMotion2-iphone.png"];

【问题讨论】:

    标签: objective-c xcode cocoa-touch uibutton uiimage


    【解决方案1】:

    有很多方法可以做到这一点。一种方法是同时监听 touch down 和 touch up 事件,在检测到 touch down 时设置图像,然后将其重置为 touch up 时的样子

    [button addTarget:self action:@selector(buttonDown:) forControlEvents:UIControlEventTouchDown];
    [button addTarget:self action:@selector(buttonUp:) forControlEvents:UIControlEventTouchUpInside];
    [button addTarget:self action:@selector(buttonUp:) forControlEvents:UIControlEventTouchUpOutside];
    

    【讨论】:

    • 我对此很陌生,由于某种原因它不起作用。我想我的代码有问题。还有其他方法吗?
    【解决方案2】:
    You have to just set different images for normal and highlighted state. 
    When the button is not pressed means in ideal state it will display 'normal.png'; 
    when the button will be pressed it will change its state to pressed and 
    highlighted now the 'highlighted.png' will be visible on button. 
    As soon as the button is released from highlighted state it will 
    come back to normal state showing the 'normal.png' again.
    
    [TapGreen setImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
    // Set image for normal state of UIButton
    [TapGreen setImage:[UIImage imageNamed:@"highlighted.png"] forState:UIControlStateSelected | UIControlStateHighlighted];
    // Set image for highlighted or pressed state of UIButton
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-25
      • 2012-02-16
      • 2014-10-16
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多