示例:设置表单
原生 Form、Section、输入控件和保存按钮。
适合做偏好设置、账号资料、功能开关页。表单使用 Form + Section,保存按钮放在 toolbar,所有输入控件都绑定命名回调。
#预期效果
运行后会出现原生设置表单,修改字段会显示未保存状态,点击保存后状态反馈更新。
#完整代码
已复制
import appui
state = appui.State(
name="Ada",
notifications=True,
theme="System",
volume=45,
last_saved="Never",
)
def set_name(value):
state.name = value
def set_notifications(value):
state.notifications = value
def set_theme(value):
state.theme = value
def set_volume(value):
state.volume = value
def save_settings():
state.last_saved = f"Saved for {state.name}"
def body():
account = appui.Section("Account", [
appui.TextField("Display name", text=state.name, on_change=set_name),
appui.Toggle("Notifications", is_on=state.notifications, on_change=set_notifications),
])
appearance = appui.Section("Appearance", [
appui.Picker(
"Theme",
selection=state.theme,
options=["System", "Light", "Dark"],
on_change=set_theme,
).picker_style("segmented"),
appui.Slider(
value=state.volume,
minimum=0,
maximum=100,
step=5,
label=f"Volume {state.volume}",
on_change=set_volume,
),
], footer="使用语义色,页面会自动适配深色模式。")
summary = appui.Section("Summary", [
appui.LabeledContent("Theme", value=state.theme),
appui.LabeledContent("Last saved", value=state.last_saved),
])
form = appui.Form([account, appearance, summary]).navigation_title("Settings")
return appui.NavigationStack(
form.toolbar([
appui.ToolbarItem(
placement="navigation_bar_trailing",
content=appui.Button(
action=save_settings,
content=appui.Label("Save", system_image="checkmark"),
).button_style("bordered_prominent"),
)
])
)
appui.run(body, state=state)
#可复用点
- 设置页默认用
Form + Section。 - 输入控件的
on_change传命名函数。 - 保存动作放在
ToolbarItem里,并且点击后要有可见状态变化。 - 需要分段选择时用
.picker_style("segmented"),不要手写一排按钮代替。