iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 26
0
Mobile Development

想知道自己iOS具現化系能力有多強嗎?實作幾個App就知道了系列 第 26

Day26-玩弄一下IBDesignable與IBInspectable來方便設置漸層功能

想要玩弄這兩個attribute,就得對他們有所了解,否則玩得不盡興,因為很有可能你設置了這兩個屬性不支援的型別,所以無法顯示在屬性檢閱器讓你玩。

IBInspectable可以支援的型別有「IntCGFloatDoubleStringBoolCGPointCGSizeCGRectUIColorUIImage」,如果你設置的型別不是這些型別的話,那屬性檢閱器將不會產生。

順帶一提,這些型別的資訊我是查閱AppCoda的書才找到的,我找不到官方文檔,希望有知道的高手幫我解惑一下官方文檔有無這些資訊。
感謝ytyubox大大的解答,已經在Documentation Archive內找到了:
https://ithelp.ithome.com.tw/upload/images/20201012/20129144lEbIhRV3l9.png


這次我打算實作一顆按鈕而已,因為這個按鈕會了,其他的東西也就都會了,我以Apple的按鈕為例,當然這個按鈕在實際上架中肯定會因為違反他們的人機介面指南而被擋下來的,所以只是示範用,直接上圖:
https://ithelp.ithome.com.tw/upload/images/20201011/2012914427OhsBJAZY.png

其他功能在上一篇都講過了,所以這次我打算講漸層的功能,並且用StoryBoard來控制這些顏色跟是否啟用漸層功能。

    @IBInspectable var 是否產生漸層: Bool = false
    @IBInspectable var 漸層開始顏色: UIColor = UIColor.black
    @IBInspectable var 漸層中間顏色: UIColor = UIColor.clear
    @IBInspectable var 漸層結束顏色: UIColor = UIColor.white

我宣告了四個屬性,相信你們肯定看得懂的。


然後建立一個漸層圖層,設定大小,並且設定顏色以及開始跟結束的位置:

func creatGradient()
    {
        if 是否產生漸層
        {
            let gradientLayer = CAGradientLayer()
            gradientLayer.frame = self.bounds
            gradientLayer.colors = [漸層開始顏色.cgColor ,漸層中間顏色.cgColor, 漸層結束顏色.cgColor]
            gradientLayer.startPoint = CGPoint(x: 0, y: 0)
            gradientLayer.endPoint = CGPoint(x: 1, y: 1)
            self.layer.insertSublayer(gradientLayer, at: 0)
        }
    }

這邊有兩點需要注意的:
1:如果沒有設置開始跟結束的位置,則是預設從上到下的漸層模式
2:在設置顏色的時候,使用UIColor.cgColor屬性,否則設置無效


creatGradient放在layoutSubviews()內,這邊需要注意的是要記得呼叫super.layoutSubviews

override func layoutSubviews() {
        super.layoutSubviews()
        creatGradient()
    }

接下來可以到屬性檢閱器點選想要的屬性設置了,需要注意到較舊版本的Xcode無法即時顯示漸層功能,需要運行模擬器才看得到:
https://ithelp.ithome.com.tw/upload/images/20201011/20129144zO57ihKQG4.png

以上就完成了,另外在這次設置的過程中,發現一件算是有坑的事情,在這裡面處理許久才發現為什麼,明天再跟大家分享。


上一篇
Day25- IBDesignable 與 IBInspectable淺談
下一篇
Day27-更改UIButton的Image大小,代誌不是你想的這麼簡單
系列文
想知道自己iOS具現化系能力有多強嗎?實作幾個App就知道了30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
ytyubox
iT邦新手 5 級 ‧ 2020-10-12 10:00:51

Interface Builder can do more than just display your custom view. You can also specify properties that can then be set in the Attributes inspector. Add the @IBInspectable attribute to the desired properties. Interface Builder supports the inspection of basic types (and their corresponding optionals), including: Booleans, numbers, strings, as well as CGRect, CGSize, CGPoint, and UIColor.

archive document 裡面喔

另外 Swift.org 在 Attributes 章節內其實沒有明說,但是有句話可以理解一下:

These attributes are conceptually the same as their Objective-C counterparts.

超級感謝!!終於找到了,另外有一點想問的是說這個Library,是舊的Document嗎? 因為我看他顯示說不再更新。https://ithelp.ithome.com.tw/upload/images/20201012/20129144XDeVyU5wUp.png

ytyubox iT邦新手 5 級 ‧ 2020-10-12 17:54:18 檢舉

什麼 Library ?簡單來說,就是很佛的文件,沒有直接刪除或更新掉。

我要留言

立即登入留言