- (void)viewDidLoad
{
[super viewDidLoad];
b1button=[UIButton buttonWithType:1];
b1button.frame=CGRectMake(0, 0, 100, 50);//位置 大小
[b1button setTitle:@"button1" forState:UIControlStateNormal];//名称
b1button.backgroundColor=[UIColor brownColor];//背景颜色
[b1button addTarget:self action:@selector(buttonpressed) forControlEvents:UIControlEventTouchUpInside];//触发事件
[self.view addSubview:b1button];//button添加入view
}
-(IBAction)buttonpressed
{
UIAlertView * alert1=[[UIAlertView alloc] initWithTitle:@"myView" message:@"hahah" delegate:self cancelButtonTitle:@"确定"otherButtonTitles:nil];
[alert1 addButtonWithTitle:@"确定2"];
[alert1 show];
}
2. NavigationBar:创建一个navigationBar,并在上面添加2个按钮,完全用代码实现没用xib。
首先创建一个navigationbar,再在上面加入navigationItem,然后在navigationItem上加入2个barButtonItem。
- (void)viewDidLoad
{
[super viewDidLoad];
UINavigationBar * navigationbar=[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];//创建导航栏
UINavigationItem * navigationitem=[[UINavigationItem alloc] initWithTitle:@"hello"];//创建导航栏集合
[navigationbar pushNavigationItem:navigationitem animated:NO];//把navigationitem合放入导航栏
UIBarButtonItem * leftbutton=[[UIBarButtonItem alloc] initWithTitle:@"left" style:UIBarButtonItemStylePlain target:self action:@selector(clickleftbutton)];//左按钮
UIBarButtonItem * rightbutton=[[UIBarButtonItem alloc] initWithTitle:@"right" style:UIBarButtonItemStyleDone target:self action:@selector(clickrightbutton)];//右按钮
[navigationitem setLeftBarButtonItem:leftbutton];//把按钮加入navigationitem
[navigationitem setRightBarButtonItem:rightbutton];
[self.view addSubview:navigationbar];
// Do any additional setup after loading the view, typically from a nib.
}
-(void) showMessage:(NSString *)str
{
UIAlertView *alertview=[[UIAlertView alloc] initWithTitle:@"hello" message:str delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alertview show];
}
-(void) clickleftbutton
{
[self showMessage:@"按了左边按钮"];
}
-(void) clickrightbutton
{
[self showMessage:@"按了右边按钮"];
}