这对我有用。
- (IBAction)buttonPressed:(id)sender {
[sender setImage:[UIImage imageNamed:@"button.jpeg"] forState:UIControlStateNormal];
[sender setTitle:(@"Aww") forState:UIControlStateNormal];
}
我确实注意到标签在最右边,而不是死点。标签是否可能在错误的位置呈现?注释掉 setTitle 会产生相同的结果,按钮标题被图像偏移。
如何将 UIImageView 变成一个按钮。注意:这很脏,应该包装到一个类中。我离开了,但注释掉了代码,只是为了做点什么。未显示的是在 xib 文件上抛出并设置为 userenabled = true 的 UIImageView。
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttonPressed:)];
[[self fakeButton] addGestureRecognizer:tap];
UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 250, 25)];
label.text = @"unpressed";
label.backgroundColor = [UIColor clearColor];
[[self fakeButton] addSubview:label];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)buttonPressed:(id)sender {
// UIGestureRecognizer *gesture = (UIGestureRecognizer*)sender;
// UIImageView* temp = (UIImageView*)gesture.view;
// for (UILabel *label in temp.subviews) {
// label.text = @"pressed";
// }
// temp.image = [UIImage imageNamed:@"button.jpeg"];
//
// //if you want it to reset after a Delay
// [self performSelector:@selector(buttonUnpressed:) withObject:temp afterDelay:.2];
}
-(void)buttonUnpressed:(UIImageView*)view
{
// for (UILabel *label in view.subviews) {
// label.text = @"unpressed";
// }
// view.image = [UIImage imageNamed:@"origButton.jpeg"];
// [self performSelector:@selector(buttonUnpressed:) withObject:view afterDelay:.2];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self.view];
if (CGRectContainsPoint([[self fakeButton] frame], point))
{
//Do touch down state
NSLog(@"touchStarted");
[[self fakeButton] setImage:[UIImage imageNamed:@"button.jpeg"]];
for (UILabel *label in [[self fakeButton] subviews]) {
label.text = @"pressed";
}
}
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"touch ended");
//remove touch down state
[[self fakeButton] setImage:[UIImage imageNamed:@"origButton.jpeg"]];
for (UILabel *label in [[self fakeButton] subviews]) {
label.text = @"unpressed";
}
}
@end