实现Label水平居中。
在XCode中拖放控件时是没有添加约束的,但你也不能随意拖放你的控件,因为在后面设置Margin时会使用到当前控件的Margin值。
建议还是拖放自己理想的位置上,方便修改布局也方便设置constraints。
1.拖放一个Label设置字体到水平居中,颜色,字号。填写内容:"Artist Name".设置Editor/Size to Fit Content.
2.拖放一个Button在下面,在代码中控制Label显示的内容。
现在我们一步一步的实现自己布局约束。
1.选中标题Label,Editor/Align/Horizontal Center in Superview(水平居中)
2.Editor/Pin/Top Space to SuperView(设置上边距)
运行程序,看到Label是居中的,内容已超出屏幕。
3.Editor/Pin/Leading Space to SuperView,Editor/Pin/Trailing Space to SuperView(设置左右间距)
运行程序,看到Label是居中的,内容会被裁剪,但内容不是居中的。
4.选择标签设置对方方式“居中对齐”
运行程序,Label中的内容不能显示全(尽管有很多空间)。
这时我们使用另一种约束叫:Inequalities。
5.选择标签的Leading Space to SuperView.将Relation值“equal”改成“Greater Than or Equal”.选中Standard复选框。
同样设置Trailing Space to SuperView.
运行程序,你可以看到Label内容会根据屏幕大小显示文字,如果太长会截取。
#pragma mark - next button
-(IBAction)nextTapped:(id)sender{
static NSArray *artists;
if(artists==nil){
artists=[[NSArray alloc] initWithObjects:@"TheLonious Monk",@"Miles Davis",
@"Jordan & His Tympany Five and long label", @"Charlie 'Bird' Parker", @"Chet Baker",nil];
}
static int index=0;
self.artistNameLabel.text=artists[index%5];
//[self.artistNameLabel sizeToFit];
index++;
}
在XCode中拖放控件时是没有添加约束的,但你也不能随意拖放你的控件,因为在后面设置Margin时会使用到当前控件的Margin值。
建议还是拖放自己理想的位置上,方便修改布局也方便设置constraints。
1.拖放一个Label设置字体到水平居中,颜色,字号。填写内容:"Artist Name".设置Editor/Size to Fit Content.
2.拖放一个Button在下面,在代码中控制Label显示的内容。
现在我们一步一步的实现自己布局约束。
1.选中标题Label,Editor/Align/Horizontal Center in Superview(水平居中)
2.Editor/Pin/Top Space to SuperView(设置上边距)
运行程序,看到Label是居中的,内容已超出屏幕。
3.Editor/Pin/Leading Space to SuperView,Editor/Pin/Trailing Space to SuperView(设置左右间距)
运行程序,看到Label是居中的,内容会被裁剪,但内容不是居中的。
4.选择标签设置对方方式“居中对齐”
运行程序,Label中的内容不能显示全(尽管有很多空间)。
这时我们使用另一种约束叫:Inequalities。
5.选择标签的Leading Space to SuperView.将Relation值“equal”改成“Greater Than or Equal”.选中Standard复选框。
同样设置Trailing Space to SuperView.
运行程序,你可以看到Label内容会根据屏幕大小显示文字,如果太长会截取。