我們可以到Switch開啟時背景色會是綠色,關掉時卻是黑色,這樣其實跟原本IPhone內建的也不一樣,
這樣眼睛看上去也不直觀,因此來幫他加個背景色吧!
不就加個背景色而已嗎?看我一行程式碼搞定他
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.backgroundColor = .clear
        // 設定accessoryView 為 UISwitch
        self.accessoryView = UISwitch(frame: .zero)
        // 設定accessoryView 背景色為 灰色
        self.accessoryView?.backgroundColor = .gray
        setViews()
        setLayouts()
    }
執行看看吧!







居然是整個正方形的背景色都變成灰色了,看來只好自己做出一個UISwitch了!
CornerRadius是讓正方體的邊邊變圓弧的參數,數字越大越圓
let accessorySwitch: UISwitch = {
        let uiSwitch = UISwitch(frame: .zero)
        // 設定 Switch 的背景色為灰色
        uiSwitch.backgroundColor = .lightGray
        // 設定 Switch 的 CornerRadius
        // CornerRadius 設為高度的一半,邊邊就會變成圓形
        uiSwitch.layer.cornerRadius = uiSwitch.frame.height / 2.0
        return uiSwitch
    }()
2.之後到init裡面更改AccessoryView,更改為我們剛剛製作的UISWitch
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.backgroundColor = .clear
        // 設定accessoryView 為 我們製作的UISwitch
        self.accessoryView = accessorySwitch
        setViews()
        setLayouts()
    }
再執行看看吧!