更换开关的按钮

Button to replace a switch

我有一个 table 视图控制器,其中包含一个颜色列表。我希望用户能够为他或她最喜欢的颜色加注星标。我目前正在使用开关来执行此操作,但我想要更具视觉吸引力的东西。我认为一个按钮可能会起作用。但是,我希望按钮具有与开关相似的属性(例如:isOn 属性)。我该怎么做?

UIButtons 也有类似开关的功能

在 IB 中,在 Interface Builder 中为 "Selected State Configuration" 设置不同的图像。

然后,将此添加到按钮的 @IBAction 中(其中 "button" 是按钮的名称):

self.button.selected = !self.button.selected

这就是存在子类化的原因。这是一个未经测试的例子:

class StarButton : UIButton {

    override var isSelected: Bool {

        willSet {

            let image = UIImage(named: newValue ? "FilledStar" : "EmptyStar")
            self.setImage(image, for: .normal)
        }
    }
}

您可以使用 tableviewcell 的 accessoryType 属性。您可以将其设置为 .checkmark

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}  

这将如下图所示