有没有一种直接的方法可以在 Kotlin IOS 中添加 UIButton 点击​​监听器?

Is there a straightforward way to add a UIButton click listener in Kotlin IOS?

addTarget(在 Kotlin 中)的签名是:

public open external expect fun addTarget(
    target: Any?,
    action: COpaquePointer? /* = CPointer<out CPointed>? */,
    forControlEvents: UIControlEvents /* = ULong */
): Unit

我想我知道如何提交 C 函数指针,但这里似乎不是这种情况...?

在这里找到了解决方案: https://discuss.kotlinlang.org/t/how-to-call-a-selector-from-kotlin-for-ios/4591

关键是使用sel_registerName创建指针并用@ObjCAction注释目标:

import kotlinx.cinterop.ObjCAction
import platform.UIKit.*
import platform.objc.sel_registerName

class MyClass() {

    val uiButton = UIButton.buttonWithType(UIButtonTypeSystem)

    init {
        uiButton.setTitle("Click me", UIControlStateNormal)
        uiButton.addTarget(this, sel_registerName("clicked"), UIControlEventTouchUpInside)
    }

    @ObjCAction
    fun clicked() {
       // React to click here...
    }

}