iOS UI开发之UIButton swift版本

作者: littleGG 发布时间: 2019-08-16 浏览: 2220 次 编辑

前言

  • UIButton是执行自定义代码以响应用户交互的控件。

  • UIButton 其实包含 UIImageView 和 UILabel 两个控件,UIButton继承于UIControl,所以有addtarget监听事件


属性和方法

初始化

let button = UIButton.init(type: .custom)

设置frame

button.frame = CGRect.init(x: 0, y: 150, width: 100, height: 100)

设置某一状态下的标题

button.setTitle("button", for: .normal)

设置某一状态下的标题颜色

button.setTitleColor(UIColor.red, for: .normal)

设置某一状态下的阴影颜色

button.setTitleShadowColor(UIColor.purple, for: .normal)

设置某一状态下的背景颜色

button.backgroundColor = UIColor.black

设置标题字体大小

button.titleLabel?.font = UIFont.systemFont(ofSize: 18)

设置某一状态下的背景图片(背景图片显示在其标题和前景图像后面。)

button.setBackgroundImage(UIImage.init(named: "imageName"), for: .normal)


设置某一状态下的前景图片

button.setImage(UIImage.init(named: "imageName"), for: .normal)

设置标题内边距

button.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)

设置图片内边距

button.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)


设置内容内边距

button.contentEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)


给按钮添加点击事件

button.addTarget(self, action: #selector(backAction), for: .touchUpInside)