ios - 如何通过关闭调用点击手势(iOS)

标签 ios swift xcode

我有一个带有 socket 的自定义 UIView。现在要设置标题和图像,我创建了一个在我的 View Controller 中调用的函数,但是当用户点击自定义 UIView 时,我想为此执行一些操作,我正在使用点击手势。所以我做了一个闭包来使用点击手势,并将它作为函数中的最后一个参数传递,但我不知道如何使用闭包调用点击手势 很抱歉,如果这看起来很愚蠢,但在这里需要一点帮助

我的 IBOutlets

@IBOutlet weak var containerView: UIView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var toggle: UISwitch!

我的关闭和点击手势

// Closure
 var onClickView: (() -> Void)?

// Tap gesture
 let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.onClickGestureRecognizerView))
    self.containerView.addGestureRecognizer(tap)

@objc func onClickGestureRecognizerView() {
    if let onClickView = onClickView {
        onClickView()
    }
}

这是我传递标题、图像和闭包的函数

func setSettingView(title: String, image: UIImage, onClickView: (() -> Void)? = nil) {
    self.title.text = title
    self.imageView.image = image
}

我只想知道当我调用该函数时如何在分配标题和图像后使用此闭包执行点击操作

我正在做这样的事情

accountInformationSettingView.setSettingView(title: "Account Information", image: #imageLiteral(resourceName: "account")) {
        self.present(AccountInformationViewController.instantiateViewController(), animated: true, completion: nil)

    }

最佳答案

在 View 的属性中分配传递的闭包。

func setSettingView(title: String, image: UIImage, onClickView: (() -> Void)? = nil) {
    self.title.text = title
    self.imageView.image = image
    self.onClickView = onClickView
}

现在当你点击 View 时,这个闭包将被调用

调用setSettingView方法时调用如下

let accountInformationSettingView = CustomView()
// setup accountInformationSettingView
let tapClosure = {
    self.present(UIViewController(), animated: true, completion: nil)
}
accountInformationSettingView.setSettingView(title: "Account Information", image: #imageLiteral(resourceName: "account"), onClickView: tapClosure)

setSettingView方法中,tapClosure会在self.onClickView中赋值

当您点击 containerView 时,将调用 onClickGestureRecognizerView 并检查 self.onClickView 是否为 nil。

然后tapClosure会被调用

关于ios - 如何通过关闭调用点击手势(iOS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55685623/

相关文章:

ios - 如何使用在函数中创建的 JSON 结果

ios - 选择 List<T> 关系的所有记录到 Results<T>?

ios - 将位置和天气信息添加到 HealthKit Workout Session

ios - 如何绘制不隐藏填充文本的 UILabel?

iOS Ad Hoc 安装失败

ios - 在另一个 View Xcode 中显示 ViewController

iphone - iOS 真的可以支持 AES 256 吗?

iphone - UILabel 超出应用程序框架

objective-c - 仅在 iOS 中首次启动时显示屏幕

ios - RxDataSources 单元重新加载动画无法正常工作