用代码创建按钮 - OC

作者: 以太死多 | 来源:发表于2015-09-06 21:32 被阅读1760次
    实例代码:
    @implementation ViewController
    
    - (void)viewDidLoad {
    [super viewDidLoad];
    
    //动态创建我们自己的按钮
    
    //1.创建按钮(UIButton)
    UIButton *button = [[UIButton alloc]init];
    
    //2.设置按钮上显示的文字
    [button setTitle:@"点我吧" forState:UIControlStateNormal];
    [button setTitle:@"摸我干啥" forState:UIControlStateHighlighted];
    
    //设置文字颜色
    [button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    [button setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];
    
    //3.加载图片
    UIImage *imgNormal = [UIImage imageNamed:@"btn_01"];
    UIImage *imgHighlighted = [UIImage imageNamed:@"btn_02"];
    
    //4.设置背景图片
    [button setBackgroundImage:imgNormal forState:UIControlStateNormal];
    [button setBackgroundImage:imgHighlighted forState:UIControlStateHighlighted];
    
    //5.设置frame属性(位置和大小)
    button.frame = CGRectMake(50, 50, 100, 100);
    
    //6.通过代码为控件注册一个单机事件
    [button addTarget:self action:@selector(buttonPrint) forControlEvents:UIControlEventTouchUpInside];
    
    
    //7.把动态创建的控件添加到控制器的view中
    [self.view addSubview:button];
    
    
    }
    
    - (void)buttonPrint{
    
       printf("测试打印");
    }
    
    - (void)didReceiveMemoryWarning {
       [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }
    
    @end

    相关文章

      网友评论

        本文标题:用代码创建按钮 - OC

        本文链接:https://www.haomeiwen.com/subject/wyiecttx.html