首页 > 解决方案 > 如何在 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()

标签: swiftxcodeuiview

解决方案


我认为委托是在 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")
  }

}

推荐阅读