1.引入命名空间
using UniRx;
2.定义一个枚举类型
public enum UIInputContentState
{
Create,
Modify,
}
3. 定义一个 ReactiveProperty 对象
public ReactiveProperty<UIInputContentState> State =
new UniRx.ReactiveProperty<UIInputContentState>(UIInputContentState.Create);
4.修改状态
BtnCancel.onClick.AddListener(()=>{
State.Value = UIInputContentState.Create;
});
5.订阅
private void Awake()
{
State.Subscribe(State =>
{
if(State == UIInputContentState.Create)
{
BtnUpdate.Hide();
BtnCancel.Hide();
InputField.text = string.Empty;
}
else
{
BtnUpdate.Show();
BtnUpdate.interactable = false;
BtnCancel.Show();
}
});
}
6.代码完整示例
/****************************************************************************
* 2019.10 DESKTOP-SF453R4
****************************************************************************/
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using QFramework;
using QF.Extensions;
using UniRx;
namespace QFramework.Afra
{
public enum UIInputContentState
{
Create,
Modify,
}
public partial class UIInputContent : UIElement
{
public ReactiveProperty<UIInputContentState> State = new UniRx.ReactiveProperty<UIInputContentState>(UIInputContentState.Create);
TodoItem mSelectedItemModel;
TodoList mTodoListModel;
public void Init(TodoList todoListModel)
{
mTodoListModel = todoListModel;
}
public void ModifyState(TodoItem selectedItemModel)
{
mSelectedItemModel = selectedItemModel;
State.Value = UIInputContentState.Modify;
InputField.text = selectedItemModel.Content;
}
private void Awake()
{
State.Subscribe(State =>
{
if(State == UIInputContentState.Create)
{
BtnUpdate.Hide();
BtnCancel.Hide();
InputField.text = string.Empty;
}
else
{
BtnUpdate.Show();
BtnUpdate.interactable = false;
BtnCancel.Show();
}
});
BtnUpdate.onClick.AddListener(() =>
{
mSelectedItemModel.Content = InputField.text;
SendMsg(new OnTodoItemUpdateMsg(mSelectedItemModel));
State.Value = UIInputContentState.Create;
});
BtnCancel.onClick.AddListener(()=>{
State.Value = UIInputContentState.Create;
});
InputField.onValueChanged.AddListener(content =>
{
if (State.Value == UIInputContentState.Modify)
{
if (BtnUpdate.interactable && content == mSelectedItemModel.Content)
{
BtnUpdate.interactable = false;
}
else if (!BtnUpdate.interactable && content != mSelectedItemModel.Content)
{
BtnUpdate.interactable = true;
}
}
});
// 监听输入完成
InputField.onEndEdit.AddListener(Content =>
{
if (State.Value == UIInputContentState.Create)
{
if (Input.GetKeyDown(KeyCode.Return))
{
SendMsg(new OnTodoItemAddedMsg(new TodoItem()
{
Completed = false,
Content = Content
}));
}
InputField.text = string.Empty;
}
});
}
protected override void OnBeforeDestroy()
{
}
}
}