以下是一个使用 C# 和 Xamarin.iOS 框架编写的简单 iOS 程序示例。这个程序创建一个带有按钮的界面,点击按钮会显示一条问候消息:
using System;
using UIKit;
namespace SimpleiOSApp
{
public partial class ViewController : UIViewController
{
private UILabel greetingLabel;
private UIButton actionButton;
public ViewController(IntPtr handle) : base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// 创建标签
greetingLabel = new UILabel()
{
Frame = new CoreGraphics.CGRect(20, 100, 280, 40),
TextAlignment = UITextAlignment.Center,
Text = "欢迎使用iOS应用"
};
View.AddSubview(greetingLabel);
// 创建按钮
actionButton = UIButton.FromType(UIButtonType.System);
actionButton.Frame = new CoreGraphics.CGRect(100, 200, 120, 40);
actionButton.SetTitle("点击我", UIControlState.Normal);
actionButton.TouchUpInside += OnButtonTapped;
View.AddSubview(actionButton);
}
// 按钮点击事件处理
private void OnButtonTapped(object sender, EventArgs e)
{
greetingLabel.Text = "你好,iOS世界!";
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
}
}
}
关键组件说明:
- ViewController:主视图控制器,管理界面生命周期
- UILabel:文本显示组件
- UIButton:按钮交互组件
- 事件处理:
TouchUpInside
事件绑定按钮点击动作
运行要求:
- 开发环境:Visual Studio for Mac 或 Windows 版 Visual Studio + Xamarin
- 依赖项:安装 Xamarin.iOS NuGet 包
- 目标平台:iOS 12.0 或更高版本
功能说明:
- 程序启动时显示默认欢迎文本
- 点击按钮后标签文本会更新为问候消息
- 使用自动布局(未展示)可适配不同屏幕尺寸
此示例展示了 iOS 应用的基本结构,包括界面创建和事件处理。实际开发中可结合 Xcode 的 Interface Builder 进行可视化设计。