美文网首页
控件 - UIButton(按钮)

控件 - UIButton(按钮)

作者: 一个七 | 来源:发表于2018-12-26 22:37 被阅读6次

    UIButton 即按钮,一般用于点击事件传递

    初始化方法

     UIButton *button = [UIButton new];
     UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
     UIButton *button = [[UIButton alloc]init];
     UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    

    添加事件

     [button addTarget:self action:@selector(show:)forControlEvents:UIControlEventTouchUpInside];
    // 参数说明  addTarget:谁来控制 ,action:事件 forControlEvents: 按钮状态(详见UIControlEvents),addTarget:谁来控制 理解可能有误
    
    -(void)show:(id)sender{
        NSLog(@"点击事件");
    }
    

    常用属性(方法)

    300C1072AC547E85E0ED2FE94E1B6B87.png

    通过系统头文件可以得知UIButton内部组成是UIImageView + UILabel,当然父类还是UIControl,所以UIView 的属性基本可以在UIButton中使用,如backgroundColor,layer...

    //设置title,即内部UILable, title:标题 ,state:状态
    - (void)setTitle:(nullable NSString *)title forState:(UIControlState)state;  // default is nil. title is assumed to be single line
    //设置按钮中 显示文字的颜色,即内部UILable的标题颜色, color:颜色 ,state:状态
    - (void)setTitleColor:(nullable UIColor *)color forState:(UIControlState)stateUI_APPEARANCE_SELECTOR; // default if nil. use opaque white
    //设置图片,即内部UIImageView 的图片 ,image:图片 ,state:状态
    - (void)setImage:(nullable UIImage *)image forState:(UIControlState)state;                     // default is nil. should be same size if different for different states
    

    创建UIButton并添加到视图

        UIButton *button = [UIButton buttonWithType:0];
        button.frame = CGRectMake(60, 150, 300, 40);
        [self.view addSubview:button];
        [button setTitle:@"你是魔鬼吗?" forState:0];
        [button addTarget:self action:@selector(touchButton:) forControlEvents:7];
        [button setTitleColor:[UIColor blueColor] forState:0];
        button.titleLabel.font = [UIFont systemFontOfSize:20];
        button.backgroundColor = [UIColor redColor];
        
        // Do any additional setup after loading the view, typically from a nib.
    }
    -(void)touchButton:(id)sender{
        UIButton *button = sender;
        if ([button.titleLabel.text isEqualToString:@"你是魔鬼吗?"]) {
            [button setTitle:@"我是你爹!" forState:0];
        }else{
            [button setTitle:@"你是魔鬼吗?" forState:0];
    
        }
    }
    
    QQ20181226-223616-HD.gif

    相关文章

      网友评论

          本文标题:控件 - UIButton(按钮)

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