简体   繁体   中英

How to create a UIImageView class that inherits from another class in Swift 5

I am trying to figure out how to create a custom UIImagView class that inherits functions from another class like a default UIViewController Class.

Code:

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")
  }
}

I need to be able to get to the Function called TestFucntion() with out doing something like this ViewController().TestFucntion() I want to be able to simply just call the function like the: TestFucntion() but the part that I'm having an issue with is that I need the CustomClass to be a UIImageView class

When you try the call TestFunction() from your new custom class it will give you this error:

Instance member 'TestFunction' cannot be used on type 'ViewController'; did you mean to use a value of this type instead?

So basically at the end of the day we need the Custom UIImageView class to be able to directly access functions from the parent UIViewController Class by simply calling then like TestFunction() not ViewController().TestFunction()

I think delegation is a good way to couple the call to testFunction() between an imageView and the controller. Add a computed property to the viewController with a custom initializer. That initializer like your code above can call 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")
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM