index.uts 1.4 KB
Newer Older
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
1
import { UIButton, UIControl } from "UIKit"
2 3 4

export class NativeButton {

5
	element : UniNativeViewElement;
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
6
	button : UIButton | null;
7

DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
8 9
	constructor(element : UniNativeViewElement) {
    // 接收组件传递过来的UniNativeViewElement
10
		this.element = element;
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
11 12
		super.init()
		this.bindView();
13 14 15
	}

	// element 绑定原生view
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
16 17 18 19 20 21 22 23 24
	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!);
25
	}
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
26 27 28 29

	updateText(text : string) {
    // 更新 button 显示文字
		this.button?.setTitle(text, for = UIControl.State.normal)
30 31 32 33 34 35
	}

	/**
	 * 按钮点击回调方法
	 * 在 swift 中,所有target-action (例如按钮的点击事件,NotificationCenter 的通知事件等)对应的 action 函数前面都要使用 @objc 进行标记。
	 */
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
36 37
	@objc buttonClickAction() {
    //构建自定义 UniNativeViewEvent 对象
38
		let event = new UniNativeViewEvent("customClick")
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
39
    //触发自定义事件
40 41 42
		this.element.dispatchEvent(event)
	}

DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
43 44 45
	destroy() {
    // 释放 UTS 实例对象,避免内存泄露
		UTSiOS.destroyInstance(this)
46 47 48
	}
}