初尝iOS开发之用代码添加按钮

原文链接:http://www.cnblogs.com/caishugeng/p/3727519.html

今天学习了用代码创建按钮,具体如下

@implementation ViewController

//创建了一个监听事件btnClik:,事件名称是btnClik: 而不是btnClik

-(void)btnClik:(UIButton *)sender

{

    NSLog(@"他摸了我");

    

}

//方法-(void)viewDidLoad是在系统初始化完view后调用的

 

- (void)viewDidLoad

{

    [superviewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    //快速创建自定义按钮,

    UIButton *button1 = [UIButtonbuttonWithType:UIButtonTypeCustom];

    //设置按钮的大小和位置

    CGRect huge = CGRectMake(50, 50, 100, 50);

    [button1 setFrame:huge ];

    //设置按钮在普通状态下的文字

    [button1 setTitle:@"别摸我"forState:UIControlStateNormal];

    //设置文字在普通状态下的颜色

    [button1 setTitleColor:[UIColorredColor] forState:UIControlStateNormal];

    //给按钮设置在普通状态下的图片

    UIImage *name1 = [UIImageimageNamed:@"sub_black_add.png"];

    [button1 setImage:name1 forState:UIControlStateNormal];

    //设置文字在高亮状态下的文字

    [button1 setTitle:@"就摸你"forState:UIControlStateHighlighted];

    //高亮状态下的文字颜色

    [button1 setTitleColor:[UIColorgreenColor] forState:UIControlStateHighlighted];

    //高亮状态下按钮的图片

    UIImage *name2 = [UIImage imageNamed:@"sub_blue_add.png"];

    [button1 setImage:name2 forState:UIControlStateHighlighted];

    //把按钮添加到view中显示出来

    [self.view addSubview:button1];

    //给按钮添加一个点击事件

    [button1 addTarget:selfaction:@selector(btnClik:) forControlEvents:UIControlEventTouchUpInside];

    

    //第二种创建按钮的方法,通过alloc创建

    UIButton *button2 =[[UIButton alloc]init];

    button2.frame = CGRectMake(100, 100, 200, 50);

    [button2 setTitle:@"你喜欢我吗" forState:UIControlStateNormal];

    [button2 setTitleColor:[UIColorpurpleColor] forState:UIControlStateNormal];

    UIImage *name3 = [UIImageimageNamed:@"sub_black_down.png"];

    [button2 setImage:name3 forState:UIControlStateNormal];

    [button2 setTitle:@"喜欢"forState:UIControlStateHighlighted];

    [button2 setTitleColor:[UIColororangeColor] forState:UIControlStateHighlighted];

    UIImage *name4 = [UIImageimageNamed:@"sub_blue_down.png"];

    [button2 setImage:name4 forState:UIControlStateHighlighted];

    [button2 addTarget:selfaction:@selector(btnClik:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:button2];

}

 

 

转载于:https://www.cnblogs.com/caishugeng/p/3727519.html

上一篇:Qt中 布局管理器失效问题


下一篇:Delphi中易混淆的概念 Owner, Parent, Self,