建立一個 UILabel
帶框架
當你知道要為標籤設定的確切尺寸時,可以使用 CGRect 框架初始化 UILabel。
迅速
let frame = CGRect(x: 0, y: 0, width: 200, height: 21)
let label = UILabel(frame: frame)
view.addSubview(label)
Objective-C
CGRect frame = CGRectMake(0, 0, 200, 21);
UILabel *label = [[UILabel alloc] initWithFrame:frame];
[view addSubview:label];
使用自動佈局
當你希望 iOS 在執行時動態計算其幀時,可以在 UILabel 上新增約束。
迅速
let label = UILabel()
label.backgroundColor = .red
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
NSLayoutConstraint.activate([
//stick the top of the label to the top of its superview:
label.topAnchor.constraint(equalTo: view.topAnchor)
//stick the left of the label to the left of its superview
//if the alphabet is left-to-right, or to the right of its
//superview if the alphabet is right-to-left:
label.leadingAnchor.constraint(equalTo: view.leadingAnchor)
//stick the label's bottom to the bottom of its superview:
label.bottomAnchor.constraint(equalTo: view.bottomAnchor)
//the label's width should be equal to 100 points:
label.widthAnchor.constraint(equalToConstant: 100)
])
Objective-C
UILabel *label = [[UILabel alloc] init];
使用 Objective-c +視覺格式語言(VFL)
UILabel *label = [UILabel new];
label.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview label];
// add horizontal constraints with 5 left and right padding from the leading and trailing
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[labelName]-5-|"
options:0
metrics:nil
views:@{@"labelName":label}]];
// vertical constraints that will use the height of the superView with no padding on top and bottom
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[labelName]|"
options:0
metrics:nil
views:@{@"labelName":label}]]
VFL 文件可以在這裡找到
建立標籤後,請務必通過自動佈局設定尺寸。如果操作不正確,Xcode 將顯示錯誤。
使用 Interface Builder
你還可以使用 Interface Builder 將 UILabel 新增到 Storyboard 或 .xib 檔案中,方法是從物件庫面板拖動 Label 並將其放入畫布中的檢視中:

Storyboard 或 .xib 不是以程式設計方式為 UILabel 指定框架(位置和大小),而是允許你使用“ 自動佈局” 向控制元件新增約束。
要訪問從 storyboard 或 xib 建立的此標籤,請建立此標籤的 IBOutlet。
Interface Builder 和 View Controller 之間的連結
一旦你將 UILabel 新增到你的 Storyboard 或 .xib 檔案,你可以通過按 Control ⌃然後在 UILabel 之間拖動滑鼠到你的 ViewController 連結到你的程式碼,或者你可以拖動到程式碼,同時右鍵單擊它以獲得它同樣的效果。

在屬性對話方塊中,你可以設定 UILabel 的名稱,並將其設定為 strong 或 weak。有關 strong 和 weak 的更多資訊,請參閱本 ,
另一種方法是以程式設計方式使插座如下:
迅速
@IBOutlet weak var nameLabel : UILabel!
Objective-C
@property (nonatomic, weak) IBOutlet UILabel *nameLabel;