iT邦幫忙

2021 iThome 鐵人賽

DAY 26
0
自我挑戰組

30天Swift純Code之旅 - 鬧鐘篇系列 第 26

Swift純Code之旅 Day26. 「客製化Switch按鈕」

前言

我們可以到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()
    }

執行看看吧!
https://ithelp.ithome.com.tw/upload/images/20211006/20108999VsHcpRkGGe.png

/images/emoticon/emoticon16.gif/images/emoticon/emoticon16.gif/images/emoticon/emoticon16.gif/images/emoticon/emoticon16.gif/images/emoticon/emoticon16.gif/images/emoticon/emoticon16.gif/images/emoticon/emoticon16.gif

居然是整個正方形的背景色都變成灰色了,看來只好自己做出一個UISwitch了!

  1. 實作一個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()
    }

再執行看看吧!


上一篇
Swift純Code之旅 Day25. 「各個TableViewHeader下的Cell顯示(2)」
下一篇
Swift純Code之旅 Day27. 「畫面最後的溫柔 - 大胎頭」
系列文
30天Swift純Code之旅 - 鬧鐘篇30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言