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

问题描述

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...
    }

}