swift - 如何在 Swift 5 中创建一个继承自另一个类的 UIImageView 类
问题描述
我试图弄清楚如何创建一个自定义 UIImagView 类,该类从另一个类(如默认 UIViewController 类)继承函数。
代码:
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")
}
}
我需要能够在不执行类似 ViewController().TestFucntion() 的情况下访问名为 TestFucntion() 的函数 我希望能够简单地调用函数,例如:TestFucntion() 但我我有一个问题是我需要 CustomClass 是 UIImageView 类
当您尝试从新的自定义类调用 TestFunction() 时,它会给您这个错误:
实例成员“TestFunction”不能用于“ViewController”类型;你的意思是使用这种类型的值吗?
所以基本上在一天结束时,我们需要自定义 UIImageView 类能够直接访问父 UIViewController 类中的函数,只需调用 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")
}
}
推荐阅读
- laravel - 如何使用 SimplePie laravel 包显示 rss 提要?
- filter - 从 Ansible 中的字符串中删除最后 n 个字符
- python - 在 Dash-plotly 按钮上运行 python 脚本
- node.js - 如何在node.js中配置不同服务器的dburl?
- windows - Jboss 7.2 - [org.jboss.config] file.encoding - Jboss 作为 Windows 服务
- javascript - 在反应中刷新后路由未定义
- python - os.path.abspath 忽略最后一个目录
- c++ - nullptr 访问类方法 VS 静态方法
- excel - 允许网络上的其他人在我的本地 PC 上打开工作簿
- sql - 无法在更新 postgres 中使用除外