LTHRadioButton
稍微受到了 Google 的材料单选按钮的启发。
下面这段视频有3个部分:全速、25% 和 10%,但转换成 GIF 后,它实际上变长了,所以 10% 的部分花费了很长时间。这里有一个 mp4 链接;如果 Safari 不行的话,请用 Chrome 尝试 - 对我来说它就是不行。
如何安装
CocoaPods
CocoaPods 是 Cocoa 项目的依赖关系管理器。你可以使用以下终端命令来安装它
gem install cocoapods
使用 CocoaPods 将 LTHRadioButton
集成到你的 Xcode 项目中,你在 Podfile 中指定它
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
use_frameworks!
target '<Your Target Name>' do
pod 'LTHRadioButton'
end
然后运行以下终端命令
pod install
手动
将 LTHRadioButton.swift
从 source
文件夹拖到您的 Xcode 项目中。
如何使用
初始化器最多可以接受3个参数:一个 diameter
,一个 selectedColor
,以及一个 deselectedColor
。它们都是可选的
diameter
的默认值是18
selectedColor
的默认值是浅蓝色deselectedColor
的默认值是UIColor.lightGray
它内部不使用 Auto Layout,但在初始化之后将具有合适的尺寸,因此您可以根据其 frame.width
和 frame.height
简单地创建约束。
属性
selectedColor
和 deselectedColor
已制成公开可定制的,用于诸如具有交替行和单选按钮颜色的 tableView
之类的场景,其中 tableView
可能会取消队列一个带有一种颜色的单元格以显示不同颜色的单元格。
isSelected
- 表示单选按钮是否被选中。
useTapGestureRecognizer
- 表示在设置回调时是否应将触摸识别器添加到控件中。此属性默认为 true
,以便可以在 onSelect
和 onDeselect
中自动添加识别器,但默认情况下不会添加识别器。
- 将其设置为
true
还会根据需要添加所需的UITapGestureRecognizer
。 - 将其设置为
false
还会删除如果原本添加了的话的UITapGestureRecognizer
。
方法
init(diameter: CGFloat = 18, selectedColor: UIColor? = nil, deselectedColor: UIColor? = nil) // Colors default internally if nil.
func select(animated: Bool = true) // Selects the radio button.
func deselect(animated: Bool = true) // Deselects the radio button.
回调
您可以使用 onSelect
和 onDeselect
方法添加要在选择/取消选中控件时运行的闭包。由于这些闭包大多数情况下是最有意义的,因此因为默认情况下没有识别器,这些方法还将添加一个(并且只有一个)UITapGestureRecognizer
到控件中,以处理触摸操作;闭包调用发生在动画开始时。
如果您想使用回调但不需要触摸识别器,可以将 useTapGestureRecognizer
设置为 false
。
示例
let radioButton = LTHRadioButton(selectedColor: .red)
container.addSubview(radioButton)
radioButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
radioButton.centerYAnchor.constraint(equalTo: container.centerYAnchor),
radioButton.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 16),
radioButton.heightAnchor.constraint(equalToConstant: radioButton.frame.height),
radioButton.widthAnchor.constraint(equalToConstant: radioButton.frame.width)]
)
radioButton.onSelect {
print("I'm selected.")
}
radioButton.onDeselect {
print("I'm deselected.")
}
[...]
radioButton.select() // I'm selected.
[...]
radioButton.deselect(animated: false) // I'm deselected.
使用此控件的应用
如果你在使用此控件,我很乐意听到你的声音!
许可
许可协议为MIT。如果你想(或需要)无需归属的许可,不要犹豫,联系我。