gpt4 book ai didi

ios - UIViewController 子类不识别 UITapGesture

转载 作者:行者123 更新时间:2023-11-28 11:28:41 25 4
gpt4 key购买 nike

为了稍微精简我的 viewcontroller,我想将 ui 元素和相应的函数移动到一个子类中。但是我的手势不起作用。我该如何解决这个问题?

MyViewController.swift

class MyViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

SubclassMyViewController().setupUserInterface(view: view)
}

@objc func doSomething() {
log.info("logo was tapped")
}

}

SubclassMyViewController.swift

class SubclassMyViewController: MyViewController {

func setupUserInterface(view: UIView) {
// ...
view.addSubview(logoImage)
logoImage.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
logoImage.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
logoImage.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5).isActive = true

}

lazy var logoImage: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "logo")

imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit

// ADD GESTURE
let tap = UITapGestureRecognizer(target: self, action: #selector(doSomething))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tap)

return imageView
}()
}

将所有内容放入 Viewcontroller 确实有效。如果我将它分成两类,手势将无法识别。谢谢!

最佳答案

我认为您在这里混淆了一些事情。

SubclassMyViewController().setupUserInterface(view: view) 此行创建了 SubclassMyViewController 的实例,在您的代码示例中它拥有 ImageView 。但是,因为您没有对创建的子类的任何引用,所以一旦该行执行完毕,它就会死掉。

您可以通过创建静态帮助程序类来实现您的目标。这是它的样子。

class MyViewController: UIViewController {

var imageView: UIImageView!

override func viewDidLoad() {
super.viewDidLoad()

MyViewControllerSetupHelper.setupUserInterface(viewController: self)
}

@objc func doSomething() {
log.info("logo was tapped")
}

}

class MyViewControllerSetupHelper {

static func setupUserInterface(viewController: MyViewController) {
let view = viewController.view!

let imageView = getLogoImageView()
viewController.imageView = imageView

let tapGesture = UITapGestureRecognizer(target: viewController, action: #selector(MyViewController.doSomething))
imageView.addGestureRecognizer(tapGesture)

view.addSubview(imageView)

NSLayoutConstraint.activate([
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
imageView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5)
])
}

static func getLogoImageView() -> UIImageView {
let imageView = UIImageView()
imageView.image = UIImage(named: "logo")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
imageView.isUserInteractionEnabled = true

return imageView
}
}

关于ios - UIViewController 子类不识别 UITapGesture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57430072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com