gpt4 book ai didi

ios - 在 Swift 中为 UIViewController 自定义 UIView

转载 作者:搜寻专家 更新时间:2023-10-31 08:16:31 25 4
gpt4 key购买 nike

我使用代码为 UIViewController 创建 View (带有 subview ),我是这样做的:

  1. 覆盖loadView()

    class MYViewController: UIViewController {

    var myView: MyView! { return self.view as MyView }

    override func loadView() {
    view = MyView()
    }
    }

这是我创建自定义 View 的方式:

class MyView: UIView {

// MARK: Initialization

override init (frame : CGRect) {
super.init(frame : frame)
addSubviews()
setupLayout()
}

convenience init () {
self.init(frame:CGRect.zero)
}

required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}

// MARK: Build View hierarchy

func addSubviews(){
// add subviews
}

func setupLayout(){
// Autolayout
}

// lazy load views
}

我为我所有的 View Controller 都这样做,我正在寻找更优雅的方法,因为这个过程是重复的,所以有没有任何解决方案可以使它变得通用,例如,创建一个 super 抽象类,或者为 UIViewController 创建一个扩展和 UIView,协议(protocol)?我是 swift 的新手,我认为 Swift 可以用它的现代模式有一个更好的优雅解决方案

最佳答案

如果您想使用自定义 View 类创建许多不同的 Controller ,我推荐的解决方案如下:

首先按照您希望能够使用它的方式实现一个自定义 View 子类,在这里我使用了您在问题中使用的那个。然后,您可以在任何需要的地方对其进行子类化,只需重写相关方法即可。

class CustomView: UIView {

// MARK: Initialization

override init(frame: CGRect) {
super.init(frame: frame)
addSubviews()
setupLayout()
}

required init() {
super.init(frame: .zero)
addSubviews()
setupLayout()
}

required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}

// MARK: Build View hierarchy

func addSubviews(){
// add subviews
}

func setupLayout(){
// Autolayout
}

}

然后创建一个通用的自定义 View Controller ,允许将类指定为通用参数,这样您就可以轻松地创建一个带有自定义 View 类的 Controller 。

class CustomViewController<T: CustomView>: UIViewController {

var customView: T! { return view as! T }

override func loadView() {
view = T()
}

init() {
super.init(nibName: nil, bundle: nil)
}

}

然后,如果您想定义一个新的自定义 View 并创建一个使用它的 Controller ,您可以简单地:

class AnotherCustomView: CustomView { /* Override methods */ }

...

let controller = CustomViewController<AnotherCustomView>()

轰!

如果您愿意,您甚至可以为这个新的 Controller 类型输入别名,以使其更加优雅:

class AnotherCustomView: CustomView { /* Override methods */ }

...

typealias AnotherCustomViewController = CustomViewController<AnotherCustomView>
let controller = AnotherCustomViewController()

关于ios - 在 Swift 中为 UIViewController 自定义 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36581470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com