iOS UI入门——使用Objective-C和Swift实现UIButton的显示和点击事件

  • Objective-C实现UIButton的显示和点击事件
-(void)setupButton{
    //初始化button
    UIButton * testButton = [UIButton buttonWithType:UIButtonTypeCustom];
    //设置位置和大小
    testButton.frame = CGRectMake(20, 300, self.view.frame.size.width - 40, 40);
    //设置背景色
    testButton.backgroundColor = [UIColor orangeColor];
    //设置标题
    [testButton setTitle:@"点我点我" forState:UIControlStateNormal];
    //设置标题颜色
    [testButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    //设置标题字体大小
    testButton.titleLabel.font = [UIFont systemFontOfSize:15];
    //设置点击事件
    [testButton addTarget:self action:@selector(testButtonClick) forControlEvents:UIControlEventTouchUpInside];
    //将button添加到父self.view上来做显示
    [self.view addSubview:testButton];
}

-(void)testButtonClick{
    NSLog(@"点啦点啦");
}
  • Swift实现UIButton的显示和点击事件
    func setupButton() {
        //初始化button
        let testButton = UIButton.init(type: UIButtonType.custom)
        //设置位置和大小
        testButton.frame = .init(x: 20, y: 300, width: self.view.frame.size.width - 40, height: 40)
        //设置背景色
        testButton.backgroundColor = UIColor.orange
        //设置标题
        testButton.setTitle("点我点我", for: UIControlState.normal)
        //设置标题颜色
        testButton.setTitleColor(UIColor.red, for: UIControlState.normal)
        //设置标题字体大小
        testButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15)
        //设置点击事件,不带参数和带参数的点击方法
        //testButton.addTarget(self,action:#selector(testButtonClick), for: .touchUpInside)  不带参数
        testButton.addTarget(self, action:#selector(buttonClick(_button:)), for: .touchUpInside)//带参数
        //将button添加到父self.view上来做显示
        self.view.addSubview(testButton)
    }

    @objc func testButtonClick(){
        print("点啦点啦")
    }

    @objc func buttonClick(_button:UIButton) {
        print(String.init(format: "点了:%@", _button))
    }

与Objective-C相比就是添加点击事件差的比较多,写的时候很容易报错,建议先写好点击方法,再去写添加点击事件的语句。
- 效果展示:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/aaaaazq/article/details/80816106