如何在 Swift 5 中创建从另一个 class 继承的 UIImageView class
How to create a UIImageView class that inherits from another class in Swift 5
我正在尝试弄清楚如何创建自定义 UIImagView class,它从另一个 class 继承功能,就像默认 UIViewController Class.
代码:
extension ViewController {
class CustomClass: UIImageView {
override init(frame: CGRect) {
super.init(frame: frame)
TestFunction()
}
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
func TestFunction() {
print("Hello")
}
}
我需要能够访问名为 TestFucntion() 的函数,而无需执行类似这样的操作 ViewController().TestFucntion() 我希望能够像这样简单地调用函数: TestFucntion() 但我遇到问题的部分是 我需要 CustomClass 成为 UIImageView class
当您尝试从您的新自定义 class 调用 TestFunction() 时,它会给您这个错误:
实例成员 'TestFunction' 不能用于类型 'ViewController';您是要改用这种类型的值吗?
所以基本上在一天结束时,我们需要自定义 UIImageView class 能够直接从父 UI ViewController Class 访问功能,只需调用 TestFunction () 不是 ViewController().TestFunction()
我认为委托是在 imageView 和控制器之间耦合对 testFunction() 的调用的好方法。使用自定义初始化程序将计算的 属性 添加到 viewController。像你上面的代码这样的初始化程序可以调用 testFunction().
protocol TestFunction {
func test()
}
class MyImageView: UIImageView {
var delegate: TestFunction?
init(frame: CGRect, tester: TestFunction? = nil) {
super.init(frame: frame)
delegate = tester
delegate?.test()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
class MyViewController: UIViewController, TestFunction {
var imageView: MyImageView? {
return MyImageView(frame: .zero, tester: self)
}
func test() {
print("test")
}
}
我正在尝试弄清楚如何创建自定义 UIImagView class,它从另一个 class 继承功能,就像默认 UIViewController Class.
代码:
extension ViewController {
class CustomClass: UIImageView {
override init(frame: CGRect) {
super.init(frame: frame)
TestFunction()
}
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
func TestFunction() {
print("Hello")
}
}
我需要能够访问名为 TestFucntion() 的函数,而无需执行类似这样的操作 ViewController().TestFucntion() 我希望能够像这样简单地调用函数: TestFucntion() 但我遇到问题的部分是 我需要 CustomClass 成为 UIImageView class
当您尝试从您的新自定义 class 调用 TestFunction() 时,它会给您这个错误:
实例成员 'TestFunction' 不能用于类型 'ViewController';您是要改用这种类型的值吗?
所以基本上在一天结束时,我们需要自定义 UIImageView class 能够直接从父 UI ViewController Class 访问功能,只需调用 TestFunction () 不是 ViewController().TestFunction()
我认为委托是在 imageView 和控制器之间耦合对 testFunction() 的调用的好方法。使用自定义初始化程序将计算的 属性 添加到 viewController。像你上面的代码这样的初始化程序可以调用 testFunction().
protocol TestFunction {
func test()
}
class MyImageView: UIImageView {
var delegate: TestFunction?
init(frame: CGRect, tester: TestFunction? = nil) {
super.init(frame: frame)
delegate = tester
delegate?.test()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
class MyViewController: UIViewController, TestFunction {
var imageView: MyImageView? {
return MyImageView(frame: .zero, tester: self)
}
func test() {
print("test")
}
}