自訂新的 UIView 類別

建立

從專案中新增檔案,選擇 Swift,檔名為新的類別名稱。 檔案建立後預設內容只有:

import Foundation

刪除後,改為新增一個新的類型,繼承自 UIView: 這個 MyView 是一個預設藍色的 UIView

import UIKit

class MyView : UIView
{

    override init(frame: CGRect)
    {
        super.init(frame: frame)
        self.backgroundColor = UIColor.blue
    }


    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

由於我們要繼承 UIView 和使用一堆 UI 相關的物件,所以得在一開始使用 import UIKit 引入這些會用到的類型。

required init? 是規定一定要有的,只是個必要的函式,直接打上就可以了。

使用

回到專案的 ViewController,在 viewDidLoad 內就可以這樣使用:

let view3 = MyView(frame: CGRect(x: 30, y: 30, width: 50, height: 50))
view.addSubview(view3)

範例:會持續變色的 UIView

import UIKit

class ColorfulView : UIView
{
    var bgHue : CGFloat = 0

    override init(frame: CGRect)
    {
        super.init(frame: frame)

        Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(self.autoChangeColor), userInfo: nil, repeats: true)
    }

    @objc func autoChangeColor()
    {
        bgHue += 0.001
        if ( bgHue > 1 )
        {
            bgHue = 0
        }
        backgroundColor = UIColor(hue: bgHue, saturation: 1, brightness: 1, alpha: 1)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
let view3 = ColorfulView(frame: CGRect(x: 30, y: 30, width: 50, height: 50))
view.addSubview(view3)

results matching ""

    No results matching ""