Swift 自定义 Loading 按钮 ContentButton

git 仓库地址:https://gitee.com/kmyhy/content-button

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。

    override func viewDidLoad() {
        super.viewDidLoad()
        lightStyleButton.style = .light
        darkStyleButton.style = .dark
        underlinedStyleButton.style = .underlined
        iconStyleButton.style = .icon
    }

在 IBAction 方法中,改变 ContentButton 的 content 属性,使它在必要的时候显示 loading 动画,然后切换回正常状态(注意在主线程中)。

    @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 将能正常工作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值