Swift学习之UIButton基础篇

UIButton的基础设置:

 func creatButton(title:String,highLightTitle:String){
       
        let button = UIButton(type:.custom);
        button.frame = CGRect(x:40,y:50,width:150,height:60);
        button.backgroundColor = UIColor.green;
        button.setTitle(title, for: UIControlState.normal);
        button.setTitle(highLightTitle, for: .highlighted);
        button.setImage(UIImage(named:"Lock"), for: .normal);
        button.setTitleColor(UIColor.orange, for: .normal);
        button.setTitleColor(UIColor.blue, for: .highlighted);
        button.titleLabel?.font = UIFont.systemFont(ofSize: 20);
        button.layer.borderColor = UIColor.yellow.cgColor;
        button.layer.borderWidth = 2.0;
        button.layer.masksToBounds = true;
        button.layer.cornerRadius = 5.0;
        button.tag = 10;
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.right;
        button.addTarget(self, action: #selector(buttonclick(sender:)), for: .touchUpInside);
        self.view.addSubview(button);
    }
    func buttonclick(sender:UIButton?){
        print("tag=",sender?.tag ?? 0);
        print("正常:",sender?.title(for: .normal) ?? "正常");
        print("高亮:",sender?.title(for: .highlighted) ?? "高亮");
        print(sender?.titleColor(for: .normal) ?? "blue");
    }

在viewdidLoad方法里调用

 creatButton(title: "我是normal",highLightTitle: "我是highlight");

效果图如下:


Swift学习之UIButton基础篇_第1张图片
效果图.png

打印结果:

tag= 10
正常: 我是normal
高亮: 我是highlight
UIExtendedSRGBColorSpace 1 0.5 0 1

你可能感兴趣的:(Swift学习之UIButton基础篇)