【问题标题】:How to create a UIImageView class that inherits from another class in Swift 5如何在 Swift 5 中创建一个继承自另一个类的 UIImageView 类
【发布时间】:2020-01-24 21:29:19
【问题描述】:

我试图弄清楚如何创建一个自定义 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() 即可

【问题讨论】:

    标签: swift xcode uiview


    【解决方案1】:

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

    【讨论】:

    • 如果视图是通过故事板创建的,控制器可以通过其 IBOutlet 设置委托。
    • 我更喜欢 Phillip 谈论的方式。然后在 viewDidLoad() 中分配委托。
    猜你喜欢
    • 2015-05-08
    • 2014-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多