gpt4 book ai didi

使用选择器通过参数传递的快速调用函数

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

我想编写一个函数来创建 View ,将它们添加到 stackView 并在单击其中一个项目时调用回调函数:这是一个简化的示例:

func createSelection(callBack:(Int)->()) {
for i in 0...5 {
let view = UIView()
// configure and fill view...
stackView.addArrangedSubview(view)
// add gesture recognizer
}
}

我的问题是,当其中一个 View 被单击时,我不知道如何调用回调函数。我不能在它上面使用选择器,因为它没有声明为 objc 函数。我该怎么做?

最佳答案

您可以为 UIView 创建一个协议(protocol),并将其用于您喜欢的任何 View 。

import UIKit

protocol Tappable {
var callback: ((Int) -> ())? { get set }
var callbackValue: Int? { get set }
func setupTapGestureRecognizer()
}

class TappableView: UIView, Tappable {
var callback: ((Int) -> ())?
var callbackValue: Int?

func setupTapGestureRecognizer() {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapGestureAction))
self.addGestureRecognizer(tapGestureRecognizer)
}

@objc func tapGestureAction() {
print("tapped")
guard let callback = callback, let callbackValue = callbackValue else { return }

callback(callbackValue)
}
}

func createSelection(callBack: @escaping (Int) -> ()) {
for i in 0...5 {
let view = TappableView()
view.callback = callBack
view.callbackValue = i
view.setupTapGestureRecognizer()
// Mocking tap action, remove this when you're done:
view.tapGestureAction()
}
}

createSelection { (value) in
print("hi from callback, with value: \(value)")
}

Playground 中的结果:

tapped
hi from callback, with value: 0
tapped
hi from callback, with value: 1
tapped
hi from callback, with value: 2
tapped
hi from callback, with value: 3
tapped
hi from callback, with value: 4
tapped
hi from callback, with value: 5

关于使用选择器通过参数传递的快速调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57441208/

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