移动端开发新手求助:Xamarin.Forms跨平台iOS秒表示例
嘿,刚接触Xamarin.Forms的话,做个秒表绝对是练手的好项目!我给你准备了一个完整的、适配iOS为主的秒表示例,代码都是基础易懂的,一步步跟着来就能跑起来~
完整Xamarin.Forms秒表示例(iOS优先)
1. 界面布局(XAML)
先在你的ContentPage里写界面,我们用简洁的布局,适配iOS的视觉风格:
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="StopwatchDemo.MainPage"> <StackLayout Padding="20" VerticalOptions="Center"> <!-- 显示计时的主标签,用iOS常用的 monospace 字体更美观 --> <Label x:Name="TimeLabel" Text="00:00:00.000" FontSize="Large" FontFamily="Courier New" HorizontalOptions="Center" Margin="0,0,0,30"/> <!-- 控制按钮组,适配iOS的按钮样式 --> <StackLayout Orientation="Horizontal" HorizontalOptions="Center"> <Button x:Name="StartPauseBtn" Text="开始" Clicked="StartPauseBtn_Clicked" BackgroundColor="#007AFF" TextColor="White" CornerRadius="8" Margin="0,0,10,0"/> <Button x:Name="ResetBtn" Text="重置" Clicked="ResetBtn_Clicked" BackgroundColor="#FF3B30" TextColor="White" CornerRadius="8"/> </StackLayout> </StackLayout> </ContentPage>
2. 后台逻辑(C#代码后台)
接下来写MainPage.xaml.cs的逻辑,用System.Timers.Timer来计时,注意必须在主线程更新UI(iOS对UI线程要求很严格):
using System; using System.Timers; using Xamarin.Forms; namespace StopwatchDemo { public partial class MainPage : ContentPage { // 计时器实例,间隔10毫秒(保证毫秒级精度) private Timer _stopwatchTimer; // 记录总计时毫秒数 private int _totalMilliseconds; // 标记当前是否在运行 private bool _isRunning; public MainPage() { InitializeComponent(); // 初始化计时器 _stopwatchTimer = new Timer(10); _stopwatchTimer.Elapsed += StopwatchTimer_Elapsed; } private void StopwatchTimer_Elapsed(object sender, ElapsedEventArgs e) { // 每次触发,增加10毫秒 _totalMilliseconds += 10; // 必须在主线程更新UI,用Device.BeginInvokeOnMainThread Device.BeginInvokeOnMainThread(() => { // 格式化时间为 时:分:秒.毫秒 var timeSpan = TimeSpan.FromMilliseconds(_totalMilliseconds); TimeLabel.Text = $"{timeSpan.Hours:D2}:{timeSpan.Minutes:D2}:{timeSpan.Seconds:D2}.{timeSpan.Milliseconds:D3}"; }); } private void StartPauseBtn_Clicked(object sender, EventArgs e) { if (_isRunning) { // 暂停计时 _stopwatchTimer.Stop(); StartPauseBtn.Text = "开始"; } else { // 开始计时 _stopwatchTimer.Start(); StartPauseBtn.Text = "暂停"; } _isRunning = !_isRunning; } private void ResetBtn_Clicked(object sender, EventArgs e) { // 停止计时器,重置数值 _stopwatchTimer.Stop(); _totalMilliseconds = 0; _isRunning = false; StartPauseBtn.Text = "开始"; // 更新UI TimeLabel.Text = "00:00:00.000"; } } }
3. iOS端专属优化
因为你主要运行在iOS上,这里给两个实用小优化:
- 提升计时器精度:如果需要更精准的计时,可以改用iOS原生的
NSTimer,不过上面的示例对新手来说已经完全够用; - 适配暗黑模式:在XAML里把背景色、文字色换成动态资源(比如
{DynamicResource PageBackgroundColor}),再在iOS项目的Info.plist里开启暗黑模式支持,就能自动适配系统主题; - 后台运行提示:如果需要后台继续计时,iOS需要开启对应权限,新手项目暂时不用,后续有需求的话可以在
Info.plist里添加UIBackgroundModes权限。
4. 运行步骤
- 打开你的Xamarin.Forms项目,新建一个
ContentPage,把上面的XAML和C#代码替换进去; - 确保你的iOS模拟器/真机已经连接好;
- 选择iOS项目作为启动项目,点击运行按钮即可。
要是你遇到问题,比如UI没更新或者计时器不跑,先检查是不是忘记调用Device.BeginInvokeOnMainThread更新UI了——iOS不允许在后台线程操作UI,这是新手常踩的小坑哦!
内容的提问来源于stack exchange,提问作者Xin Ning
相关产品推荐
相关产品推荐

