I need your help to create a button dyn开发者_JAVA百科amically in iphone
Thanks
Cut and paste this into a View-based project's ProjectViewController.m file:
- (void) pressed:(id)sender
{
NSLog( @"pressed!" );
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.contentMode = UIViewContentModeScaleToFill;
UIImage *img = [UIImage imageNamed:@"myimage.png"];
[btn setBackgroundImage:img forState:UIControlStateNormal];
[btn setTitle:@"Button Title" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(pressed:) forControlEvents:UIControlEventTouchUpInside];
btn.frame = CGRectMake( 20, 20, 200, 100 );
[self.view addSubview:btn];
}
The main thing to remember is that setBackgroundImage:forState:
will stretch the image to fill the button's frame, while setImage:forState:
will not.
精彩评论