diff --git a/docs/component/native-view.md b/docs/component/native-view.md index 9704c75c7f074d1549a3c7799950f19c9eeaa8bc..88de17f3e78110826ee9f732b2575482b1f9abf5 100644 --- a/docs/component/native-view.md +++ b/docs/component/native-view.md @@ -51,7 +51,159 @@ - + + +native-button 组件代码实现如下: +```uts + + + +``` + +NativeButton原生对象代码如下: + +::: preview + +> Android + +```uts +import { Button } from "android.widget" + +export class NativeButton { + $element: UniNativeViewElement; + + constructor(element: UniNativeViewElement) { + this.$element = element; + this.bindView(); + } + + button: Button | null = null; + bindView() { + //通过UniElement.getAndroidActivity()获取android平台activity 用于创建view的上下文 + this.button = new Button(this.$element.getAndroidActivity()!); //构建原生view + //限制原生Button 文案描述不自动大写 + this.button?.setAllCaps(false) + //监听原生Button点击事件 + this.button?.setOnClickListener(_ => { + const detail = {} + //构建自定义UniNativeViewEvent返回对象 + const event = new UniNativeViewEvent("customClick", detail) + //响应分发原生Button的点击事件 + this.$element.dispatchEvent(event) + }) + //UniNativeViewEvent 绑定 安卓原生view + this.$element.bindAndroidView(this.button!); + } + + updateText(text: string) { + //更新原生Button 文案描述 + this.button?.setText(text) + } + + destroy() { + //数据回收 + } +} +``` + +> iOS + +```uts +import { UIButton, UIControl } from "UIKit" + +export class NativeButton { + + element : UniNativeViewElement; + button : UIButton | null; + + constructor(element : UniNativeViewElement) { + // 接收组件传递过来的UniNativeViewElement + this.element = element; + super.init() + this.bindView(); + } + + // element 绑定原生view + bindView() { + // 初始化原生 UIButton + this.button = new UIButton(type=UIButton.ButtonType.system) + // 构建方法选择器 + const method = Selector("buttonClickAction") + // button 绑定点击回调方法 + button?.addTarget(this, action = method, for = UIControl.Event.touchUpInside) + // UniNativeViewElement 绑定原生 view + this.element.bindIOSView(this.button!); + } + + updateText(text : string) { + // 更新 button 显示文字 + this.button?.setTitle(text, for = UIControl.State.normal) + } + + /** + * 按钮点击回调方法 + * 在 swift 中,所有target-action (例如按钮的点击事件,NotificationCenter 的通知事件等)对应的 action 函数前面都要使用 @objc 进行标记。 + */ + @objc buttonClickAction() { + //构建自定义 UniNativeViewEvent 对象 + let event = new UniNativeViewEvent("customClick") + //触发自定义事件 + this.element.dispatchEvent(event) + } + + destroy() { + // 释放 UTS 实例对象,避免内存泄露 + UTSiOS.destroyInstance(this) + } +} + +``` + +::: + +具体示例请参考:[native-button](https://gitcode.net/dcloud/hello-uni-app-x/-/blob/alpha/uni_modules/native-button/components/native-button/native-button.uvue)插件