在 iOS,UIButton 类表示按钮控件。
可以通过编程方式或使用 Xcode 的 Interface Builder 修改按钮的属性。
以编程方式创建按钮
只需几行代码即可创建一个 UIButton。
- 实例化按钮并指定其类型: - UIButton myButton = new UIButton(UIButtonType.System);- 按钮的类型由 - UIButtonType属性指定:- UIButtonType.System- 常规用途按钮
- UIButtonType.DetailDisclosure- 指示详细信息的可用性,通常与表中的特定项有关
- UIButtonType.InfoDark- 指示配置信息的可用性;深色
- UIButtonType.InfoLight- 指示配置信息的可用性;浅色
- UIButtonType..AddContact- 指示可以添加联系人
- UIButtonType.Custom- 可自定义按钮
 - 有关不同按钮类型的详细信息,请查看: - 本文档的自定义按钮类型部分
- 按钮类型方案
- Apple 的 iOS 人机界面指南。
 
- 定义按钮的大小和位置: - myButton.Frame = new CGRect(25, 25, 300, 150);
- 设置按钮的文本。 使用 - SetTitle方法,该方法需要用到文本和- UIControlState按钮状态的值:- myButton.SetTitle("Hello, World!", UIControlState.Normal);- 下面列出了按钮的状态类型: - UIControlState.Normal
- UIControlState.Highlighted
- UIControlState.Disabled
- UIControlState.Selected
- UIControlState.Focused
- UIControlState.Application
- UIControlState.Reserved
 - 有关设置按钮样式及其文本的详细信息,请参阅: 
处理按钮点击
若要响应按钮点击,请提供按钮 TouchUpInside 事件的处理程序:
myButton.TouchUpInside += (sender, e) => {
    DoSomething();
};
注意
TouchUpInside 不是唯一可用的按钮事件。 UIButton 是 UIControl 的子类,后者定义了许多不同的事件。
设置按钮样式
UIButton 控件存在多种不同状态,每个状态由 UIControlState 值 – Normal、Disabled、Focused、Highlighted 等指定。每个状态都可以通过编程方式或使用 iOS 设计器指定唯一样式。
注意
有关所有 UIControlState 值的完整列表,请查看 UIKit.UIControlState enumeration 文档。
例如,若要为 UIControlState.Normal 设置标题颜色和阴影颜色:
myButton.SetTitleColor(UIColor.White, UIControlState.Normal);
myButton.SetTitleShadowColor(UIColor.Black, UIControlState.Normal);
以下代码将为按钮标题设置 UIControlState.Normal 和 UIControlState.Highlighted 的属性化(风格化)字符串:
var normalAttributedTitle = new NSAttributedString(buttonTitle, foregroundColor: UIColor.Blue, strikethroughStyle: NSUnderlineStyle.Single);
myButton.SetAttributedTitle(normalAttributedTitle, UIControlState.Normal);
var highlightedAttributedTitle = new NSAttributedString(buttonTitle, foregroundColor: UIColor.Green, strikethroughStyle: NSUnderlineStyle.Thick);
myButton.SetAttributedTitle(highlightedAttributedTitle, UIControlState.Highlighted);
自定义按钮类型
UIButtonType 类型的 Custom 按钮没有默认样式。 但是,可以通过为按钮的不同状态设置图像来配置按钮的外观:
myButton.SetImage (UIImage.FromBundle ("Buttons/MagicWand.png"), UIControlState.Normal);
myButton.SetImage (UIImage.FromBundle ("Buttons/MagicWand_Highlight.png"), UIControlState.Highlighted);
myButton.SetImage (UIImage.FromBundle ("Buttons/MagicWand_On.png"), UIControlState.Selected);
根据用户是否触摸按钮,它将分别呈现为以下图像之一(UIControlState.Normal、UIControlState.Highlighted 以及 UIControlState.Selected 状态):



有关使用自定义按钮的详细信息,请参阅使用图像作为按钮方案。