測試動態button傳遞變數的方法
1. 開啓專案
2. 在mainViewController.h設定Label變數
#import <UIKit/UIKit.h>
@interface mainViewController : UIViewController
@property (nonatomic) UILabel *helloLabel;
@end
3. 在mainViewController.m加入動態Button的程式碼
#import "mainViewController.h"
@interface mainViewController ()
@end
@implementation mainViewController
@synthesize helloLabel;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self setButton:1];
[self setButton:2];
[self setLabel];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)setLabel {
helloLabel = [[UILabel alloc] init];
helloLabel.frame = CGRectMake(200, 100 ,200, 100);
//helloLabel.center = self.view.center;
helloLabel.backgroundColor = [UIColor blueColor];
helloLabel.textAlignment = UITextAlignmentCenter;
helloLabel.text =@"Label";
[self.view addSubview:helloLabel];
}
- (void)setButton:(int) tag
{
UIButton *_helloActionButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
_helloActionButton.frame = CGRectMake(0,0, 100, 30);
//_helloActionButton.center = self.view.center;
[_helloActionButton setCenter:CGPointMake(100, 50 + tag*150)];
_helloActionButton.tag = tag;
[_helloActionButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
//_helloActionButton.= @"Action Button";
[_helloActionButton setTitle:[NSString stringWithFormat:@"Button%d",tag] forState:UIControlStateNormal];
[self.view addSubview:_helloActionButton];
}
-(void) buttonPressed : (id) sender{
UIButton *clicked = (UIButton *) sender;
helloLabel.text =[NSString stringWithFormat:@"Button%d Pressed",clicked.tag];
}
@end
4. 結果




沒有留言:
張貼留言