You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Xamarin UI Test验证iOS应用中复选框的选中状态

嘿,我来帮你搞定iOS上用Xamarin UI Test验证复选框选中状态的问题,同时也给你讲讲iOS原生层面的验证方法!

在Xamarin UI Test中验证iOS复选框选中状态

首先得明确:iOS里的"复选框"通常分两种常见情况——原生的UISwitch(开关控件,很多场景下充当复选框),或者自定义的UIButton(用不同状态的图片模拟复选框)。针对不同控件,验证方式略有区别:

1. 验证原生UISwitch的选中状态

原生UISwitch的选中状态由isOn属性控制,对应Xamarin UI Test的代码如下:

// 假设你的UISwitch的Accessibility Identifier设置为"mySwitch"
var isSwitchChecked = app.Query(c => c.Marked("mySwitch").Invoke("isOn").Value()).First();
// 断言选中状态
Assert.IsTrue((bool)isSwitchChecked);

这里用Marked()来定位控件,因为iOS中我们通常给控件设置Accessibility Identifier(在Storyboard或代码里设置AccessibilityIdentifier属性),Marked()可以直接匹配这个标识。

2. 验证自定义UIButton实现的复选框

如果是用UIButton自定义的复选框(通过selected状态切换图片),那它的选中状态由isSelected属性控制,代码如下:

// 假设自定义复选框的Accessibility Identifier是"customCheckbox"
var isCheckboxSelected = app.Query(c => c.Marked("customCheckbox").Invoke("isSelected").Value()).First();
Assert.IsTrue((bool)isCheckboxSelected);
iOS原生层面的验证方法

如果你需要直接在iOS项目内(比如用XCTest做原生UI测试)验证,或者在Xamarin UI Test中调用原生逻辑,有两种实用方式:

1. 用XCTest原生测试

在Xamarin.iOS的UITest项目中,你可以直接访问iOS原生控件的属性:

// 获取应用实例
var app = new XCUIApplication();
app.Launch();

// 定位UISwitch并验证状态
var mySwitch = app.Switches["mySwitch"];
Assert.IsTrue(mySwitch.Value.ToString() == "1"); // 1代表选中,0代表未选中
// 或者直接检查选中状态属性
Assert.IsTrue(mySwitch.IsSelected);

// 定位自定义UIButton并验证
var customCheckbox = app.Buttons["customCheckbox"];
Assert.IsTrue(customCheckbox.IsSelected);

2. 在Xamarin UI Test中调用原生代码

如果想在跨平台的Xamarin UI Test里执行原生验证逻辑,可以用app.Invoke()方法调用iOS项目中暴露的原生方法:
首先在iOS项目的AppDelegate里添加一个方法:

[Export("isCheckboxSelected:")]
public bool IsCheckboxSelected(string accessibilityId)
{
    var window = UIApplication.SharedApplication.KeyWindow;
    var checkbox = window.ViewWithAccessibilityIdentifier(accessibilityId) as UIButton;
    return checkbox?.IsSelected ?? false;
}

然后在Xamarin UI Test中调用:

var isSelected = app.Invoke("isCheckboxSelected:", "customCheckbox");
Assert.IsTrue((bool)isSelected);

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:49:18