有没有一种简单的方法可以在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...
}
}

最新更新