gpt4 book ai didi

ios - 从 Kotlin Native 继承 UIView

转载 作者:行者123 更新时间:2023-12-04 12:27:47 27 4
gpt4 key购买 nike

UIKit 旨在通过子类和覆盖方法使用。
通常,drawRect UIView的objective-C方法在SWIFT中是这样实现的:

import UIKit
import Foundation

class SmileView: UIView {
override func draw(_ rect: CGRect) {
super.draw(rect)

let smile = ":)" as NSString
smile.draw(in: rect, withAttributes: nil)
}
}
不幸的是,Kotlin 中的 UIKit 导入将这些函数定义为无法覆盖的扩展函数。
有没有人通过自定义 cinterop 成功地从 Kotlin 继承 UIView?配置?

最佳答案

所以我们设法让它发挥作用。
1. 在 build.gradle.kts 添加 cinterop 配置任务

kotlin {
android()
ios {
binaries {
framework {
baseName = "shared"
}
}
compilations.getByName("main") {
val uikit by cinterops.creating {
}

}
}
2. 添加一个 `src/nativeinterop/cinterop/uikit.def` 文件。
package = demo.cinterop
language = Objective-C
---

#import <Foundation/Foundation.h>
#import <UIKit/UIView.h>

@protocol UIViewWithOverrides
- (void) drawRect:(CGRect)aRect;
- (void) layoutSubviews;
@end

3.创建自定义UIView类
该类从 UIKit 扩展了 UIView 并实现了之前创建的 UIViewWithOverrides 协议(protocol) (自动添加后缀)
package demo

import demo.cinterop.UIViewWithOverridesProtocol
import kotlinx.cinterop.*
import platform.CoreGraphics.*
import platform.UIKit.*

@ExportObjCClass
class MyView() : UIView(frame = CGRectMake(.0, .0, .0, .0)), UIViewWithOverridesProtocol {

override fun layoutSubviews() {
println("layoutSubviews")
setNeedsDisplay()
}

override fun drawRect(aRect: CValue<CGRect>) {
val rectAsString = aRect.useContents {
"" + this.origin.x + ", " + this.origin.y + ", " + (this.origin.x +this.size.width) + ", " + (this.origin.y +this.size.height)
}
println("drawRect:: Rect[$rectAsString]")

val context: CPointer<CGContext>? = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, 2.0)
val components = cValuesOf(0.0, 0.0, 1.0, 1.0)
CGContextSetFillColor(context, components)
val square = CGRectMake(100.0, 100.0, 200.0, 200.0)
CGContextFillRect(context, square)

}

}

fun createMyView(): UIView = MyView()

4. 从 Swift 使用它
struct ChartView: View {

var body: some View {

VStack {
Text("Chart View")
MyView()
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
}
}

}

struct ChartView_Previews: PreviewProvider {
static var previews: some View {
ChartView()
}
}

struct MyView: UIViewRepresentable {

func makeUIView(context: Context) -> UIView {
UIChartViewKt.createMyView()
}

func updateUIView(_ uiView: UIView, context: Context) {
}

}

关于ios - 从 Kotlin Native 继承 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69266205/

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