iOS开发基础2-基础控件详解:UILabel、UIImageView 与 UIButton
iOS 基础控件详解:UILabel、UIImageView 与 UIButton
在 iOS 开发中,UILabel、UIImageView 和 UIButton 是三个最常用的 UI 组件。理解它们的特点、用法及底层实现,有助于在不同场景下做出正确选择。
一、UILabel
UILabel 用于显示只读文本,支持单行/多行、富文本、字体、颜色、对齐方式等样式设置。
特点
- 轻量级:专为静态文本展示设计,不支持编辑。
- 多行文本:通过
numberOfLines属性控制行数,设为0表示自动换行。 - 富文本支持:通过
NSAttributedString设置混合样式(不同字号、颜色、行距等)。 - 易于使用:代码或 Interface Builder 均可快速配置。
用法示例
Objective-C
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 50, 300, 50)];
label.text = @"Hello, World!";
label.font = [UIFont boldSystemFontOfSize:18];
label.textColor = [UIColor blackColor];
label.textAlignment = NSTextAlignmentCenter;
label.numberOfLines = 0; // 自动换行,显示多行
[self.view addSubview:label];
Swift
let label = UILabel(frame: CGRect(x: 10, y: 50, width: 300, height: 50))
label.text = "Hello, World!"
label.font = .boldSystemFont(ofSize: 18)
label.textColor = .black
label.textAlignment = .center
label.numberOfLines = 0 // 自动换行,显示多行
view.addSubview(label)
底层实现
UILabel是UIView的子类,只读,不支持文本编辑。- 从 iOS 7 开始,文本排版基于 Text Kit 框架(其下基于 Core Text)。
text、font、textColor、textAlignment等属性会被合成为内部的NSAttributedString。- 文本绘制发生在
drawTextInRect:方法中,子类可重写该方法自定义绘制。 - 默认
userInteractionEnabled = NO,不响应触摸;如需交互可手动开启并添加手势识别器。
二、UIImageView
UIImageView 用于显示图片,支持静态图片和帧动画。
特点
- 高效的图片呈现:专为图片展示优化,渲染性能好。
- 动画支持:通过
animationImages设置一组图片,实现帧动画。 - 内容模式:支持
scaleToFill、aspectFit、aspectFill等多种contentMode,控制图片如何缩放填充。
用法示例
Objective-C
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 110, 300, 200)];
imageView.image = [UIImage imageNamed:@"example.png"];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[self.view addSubview:imageView];
Swift
let imageView = UIImageView(frame: CGRect(x: 10, y: 110, width: 300, height: 200))
imageView.image = UIImage(named: "example.png")
imageView.contentMode = .scaleAspectFit
view.addSubview(imageView)
帧动画示例
Objective-C
imageView.animationImages = @[
[UIImage imageNamed:@"frame1"],
[UIImage imageNamed:@"frame2"],
[UIImage imageNamed:@"frame3"]
];
imageView.animationDuration = 1.0; // 一轮动画时长(秒)
imageView.animationRepeatCount = 0; // 0 表示无限循环
[imageView startAnimating];
Swift
imageView.animationImages = [
UIImage(named: "frame1")!,
UIImage(named: "frame2")!,
UIImage(named: "frame3")!
]
imageView.animationDuration = 1.0
imageView.animationRepeatCount = 0 // 无限循环
imageView.startAnimating()
底层实现
UIImageView是UIView的子类。- 设置
image属性时,底层将UIImage的CGImage赋值给自身layer.contents,由 Core Animation 负责渲染。 contentMode对应layer.contentsGravity,决定图片在图层内的缩放与对齐方式。- 帧动画本质是定时切换
layer.contents的内容。 - 默认
userInteractionEnabled = NO;如需点击交互可手动开启并添加UITapGestureRecognizer。
三、UIButton
UIButton 是可触发用户操作的按钮控件,支持文字、图片及多种状态外观。
特点
- 丰富的状态控制:可针对
normal(正常)、highlighted(高亮)、selected(选中)、disabled(禁用)四种状态分别设置标题、图片、背景色。 - 多种按钮类型:
system(系统按钮,默认蓝色文字)、detailDisclosure、infoLight、contactAdd、close等。 - 事件响应:基于
target-action机制,支持touchUpInside、touchDown、touchDragInside等多种触摸事件。
用法示例
Objective-C
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(10, 330, 300, 50);
[button setTitle:@"Click Me" forState:UIControlStateNormal];
[button addTarget:self
action:@selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
- (void)buttonClicked:(UIButton *)sender {
NSLog(@"Button clicked!");
}
Swift
let button = UIButton(type: .system)
button.frame = CGRect(x: 10, y: 330, width: 300, height: 50)
button.setTitle("Click Me", for: .normal)
button.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)
view.addSubview(button)
@objc func buttonClicked(_ sender: UIButton) {
print("Button clicked!")
}
iOS 15+ 现代 API:UIButton.Configuration
iOS 15 引入了 UIButton.Configuration,以声明式方式统一配置按钮外观:
Objective-C
UIButtonConfiguration *config = [UIButtonConfiguration filledButtonConfiguration];
config.title = @"Click Me";
config.baseBackgroundColor = [UIColor systemBlueColor];
config.baseForegroundColor = [UIColor whiteColor];
config.cornerStyle = UIButtonConfigurationCornerStyleMedium;
UIButton *button = [UIButton buttonWithConfiguration:config primaryAction:nil];
button.frame = CGRectMake(10, 330, 300, 50);
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
Swift
var config = UIButton.Configuration.filled()
config.title = "Click Me"
config.baseBackgroundColor = .systemBlue
config.baseForegroundColor = .white
config.cornerStyle = .medium
let button = UIButton(configuration: config)
button.frame = CGRect(x: 10, y: 330, width: 300, height: 50)
button.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)
view.addSubview(button)
底层实现
UIButton继承自UIControl,而UIControl继承自UIView。- 按钮内部包含一个
UILabel(titleLabel)和一个UIImageView(imageView)作为子视图,分别展示标题和图片。 - 不同状态(normal / highlighted / selected / disabled)对应不同的标题、图片、背景图和标题颜色;状态切换时,按钮更新子视图的内容,并非每个状态对应一个独立的 CALayer。
- 交互通过
UIControl的 target-action 机制处理:调用addTarget:action:forControlEvents:注册事件,触摸时由UIControl跟踪触摸轨迹并触发对应事件,最终调用注册的方法。
四、总结对比
| 维度 | UILabel | UIImageView | UIButton |
|---|---|---|---|
| 继承链 | UIView | UIView | UIControl → UIView |
| 核心用途 | 显示只读文本 | 显示图片/帧动画 | 响应用户点击操作 |
| 默认可交互 | 否(可手动开启) | 否(可手动开启) | 是 |
| 状态管理 | 无状态 | 无状态 | 4 种状态(normal/highlighted/selected/disabled) |
| 事件机制 | 需手动加手势 | 需手动加手势 | 内置 target-action |
UILabel
- 优点:轻量级,静态文本展示简单高效,支持富文本和多行。
- 局限:只读,不支持文本编辑;默认不响应用户交互。
UIImageView
- 优点:图片渲染高效,支持帧动画,多种内容模式适配不同布局。
- 局限:仅用于图片展示,默认不响应用户交互。
UIButton
- 优点:内置多状态外观管理,丰富的触摸事件,开箱即用的交互能力。
- 局限:相比纯展示控件配置项更多;自定义复杂外观时需要处理状态间的样式切换。
五、选型建议
- 需要展示静态文字 →
UILabel - 需要展示图片或简单帧动画 →
UIImageView - 需要用户点击触发操作 →
UIButton - 需要展示文字/图片且可点击 → 优先用
UIButton(同时设置 title 和 image),而非给UILabel/UIImageView加手势——按钮的状态高亮、事件跟踪都是原生支持的。
选择合适的控件不仅能提升性能,也能让交互逻辑更清晰、维护成本更低。
将来的你会感谢今天如此努力的你!
版权声明:本文为博主原创文章,未经博主允许不得转载。

浙公网安备 33010602011771号