# ContentButton **Repository Path**: kmyhy/content-button ## Basic Information - **Project Name**: ContentButton - **Description**: No description available - **Primary Language**: Swift - **License**: 0BSD - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2022-02-23 - **Last Updated**: 2022-02-23 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Loading 按钮 App 中经常会用到这样的按钮,当你点击它,它会显示一个 loading 图标并不停地转圈(小菊花),表示它正在异步加载某些数据,当加载完成,按钮才恢复原样: 这正是 ContentButton 能为你做的。它的使用非常简单,直接将源文件放到你的项目中即可: * ContentButton.swift ContentButton 还用到了一个 UIColor 的扩展函数 init(hexString: ),定义在下面的文件中,你可能还需要引入它: * UIColor+extension.swift 然后你就可以在你的 ViewController 中使用 ContentButton 了。最简单的方式是通过故事板。拖一个 UIButton 到你的 ViewController,修改 class 为 ContentButton。然后你可以像使用普通的 UIButton 一样,为它创建 IBOutlet 和 IBAction 连接,并定制它的外观,文本、字体、颜色、圆角等等。 当前 ContentButton 支持 4 种 style,它们的外观和 loading 效果正如上面的截屏所示。你可以在 viewDidLoad 方法中,为 contentButton 指定一种 style。 ```swift override func viewDidLoad() { super.viewDidLoad() lightStyleButton.style = .light darkStyleButton.style = .dark underlinedStyleButton.style = .underlined iconStyleButton.style = .icon } ``` 在 IBAction 方法中,改变 ContentButton 的 content 属性,使它在必要的时候显示 loading 动画,然后切换回正常状态(注意在主线程中)。 ```swift @IBAction func contentButtonAction(_ sender: ContentButton) { sender.content = .inProgress DispatchQueue.global().async { // do something DispatchQueue.main.asyncAfter(deadline: .now()+2.0) { sender.content = .default } } } ``` content 属性有两个取值: * .inProgress :disabled 状态下显示 loading 动画 * .default : normal 状态 值得注意的是 icon style,它需要你为 ContentButton 提供两张,图片,一张用于正常状态的按钮背景,一张用于 loading 状态,比如 demo 中所用的这两张: 将这两张图片分别用于 ContentButton 的 Default 状态和 Disabled 状态,icon style 将能正常工作。