©️ OverlookArt
首页 / AppleDevelop / UIKit / UIButton

UIButton

快速使用

  • 初始化: init(type:)
  • 设置标题: setTitle(_:for:)
  • 设置标题颜色: setTitleColor(_:for:)
  • 设置图标: setImage(_:for:)
  • 设置背景图片: setBackgroundImage(_:for:)
  • 添加点击事件: addTarget(_:action:for:)
 1let button = UIButton(type: .custom)
 2button.setTitle("按钮标题", for: .normal)
 3button.setTitleColor(.link, for: .normal)
 4button.setImage(UIImage(systemName: "xmark.circle"), for: .normal)
 5button.setBackgroundImage(UIImage(named: "icon"), for: .normal)
 6button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
 7
 8@objc private func buttonAction(){
 9    debugPrint("按钮点击事件")
10}

水平对齐

通过设置 contentHorizontalAlignment 属性来改变 UIButton 的内容(图标和标题)水平对齐方式。 该属性有6个枚举值:

  • center
  • left
  • right
  • fill
  • leading(iOS 11.0, *)
  • trailing(iOS 11.0, *)
1let button = UIButton(type: .system)
2button.setTitle("按钮标题", for: .normal)
3button.contentHorizontalAlignment = .left

内容边距

通过设置 contentEdgeInsets 属性来改变 UIButton 的内容(图标和标题)上、下、左、右边距。

1et button = UIButton(type: .system)
2button.setTitle("按钮标题", for: .normal)
3button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)