实现了一个只读的text view。UILabel内容的默认模式为:UIViewContentModeRedraw,在这种模式下,每当label的边界改变时会重新绘制内容。
UILabel基础
访问text属性
- @property (nonatomic, copy) NSString * text
- label中显示的文本
- @property (nonatomic, copy) NSAttributedString * attributedText
- label显示的样式文本。对该属性的赋值会更新font和textColor,以及其他相关的属性。
- @property (nonatomic, retain) UIFont * font
- 文本的字体。iOS常用字体
- @property (nonatomic, retain) UIColor * textColor
- 文本的颜色
- @property (nonatomic) NSTextAlignment textAlignment
- 文本的对齐技术。在iOS6及之后的版本中,对该属性的赋值会导致文本对齐方式应用到attibutedText属性的整个字符串。如果希望只应用到部分文本,则需要创建一个拥有期待样式信息的新的attributed字符串,并将其与label关联。
- 对齐方式类型:
- @property (nonatomic) lineBreakMode
- 封装和缩短lebel中文本的技术。如果没有使用样式文本,则该属性应用到整个文本字符串。如果使用样式文本,在iOS6及之后的版本中,对该属性的赋值会导致换行模式应用到attributedText属性的整个字符串中。如果希望只应用到部分文本,则需要创建一个拥有期待样式信息的新的attributed字符串,并将其与label关联。
- @property (nonatomic, getter=isEnabled) BOOL enabled
- 当绘制label文本时使状态可用。该属性仅决定label如何绘制,不可用的问题是模糊的以表示它不可用,默认为YES。
调整label text的大小
- @property (nonatomic) BOOL adjustsFontSizeToFitWidth
- 表示字体大小是否应该减少以适应label边界内的title字符串。通常情况下,lebel的文本按照font的设置进行显示,但如果该值设置为YES,则当文本超过label边界时会自动减少字体大小直到适应了label边界或者达到了字体的最小值。
- @property (nonatomic) UIBaselineAdjustment baselineAdjustment
- 控制当文本需要减少以适应label时的基准线。如果adjustsFontSizeToFitWidth设置为YES,则这个属性在字体大小需要调整时控制文本基准线的行为。默认值为UIBaselineAdjustmentAlignBaselines。该属性只有当numberOfLines属性设置为1时才有效。
- @property (nonatomic) CGFloat minimumScaleFactor
- label文本支持的最小大小因子。通过该属性能够在现实label文本时指定当前字体大小下最小的乘数,产生一个何时的用于现实的字体大小。如果设置为0,则当前字体大小为最小字体大小
- @property (nonatomic) numberOfLines
- 产生文本的最大行数
管理强调值
- @property (nonatomic, retain) UIColor * highlightedTextColor
- label文本强调状态时的颜色
- @property (nonatomic, getter=isHighlighted) highlighted
- 表示receiver是否应该绘制一个强调的文本
绘制或者位置重写
- @property (nonatomic) UIColor * shadowColor
- 文本的阴影颜色
- @property (nonatomic) shadowOffset
- 文本阴影偏移量
设置和获取属性
- @property (nonatomic) userInteractionEnabled
- 表示是否忽略用户事件,将其从事件队列中移除。
获得布局限制
- @property (nonatomic) CGFloat perferredMaxLayoutWidth
- 多行label中的最大宽度
实例
基础
定义一个UILabel,设置其文本和背景颜色。
-(void)initTitle:(int)x yCoordinate:(int)y{
titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, 200, 40)];
titleLabel.text = @"About";
titleLabel.backgroundColor = [UIColor yellowColor];
[self addSubview:titleLabel];
}
具体显示如下:
从上图可以看出,该Label显示的不好看。我们希望改变label中文本的对齐方式以及label的文本颜色等,可以通过一下方式完成:
-(void)initTitle:(int)x yCoordinate:(int)y{
titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, 200, 40)];
titleLabel.text = @"About";
titleLabel.backgroundColor = [UIColor yellowColor];
<span style="color:#993399;">//Style
titleLabel.textAlignment = NSTextAlignmentCenter;
titleLabel.textColor = [UIColor purpleColor];
titleLabel.font = [UIFont fontWithName:@"American Typewriter" size:22.0];
titleLabel.shadowColor = [UIColor redColor];
titleLabel.shadowOffset = CGSizeMake(20, 5);</span>
[self addSubview:titleLabel];
}
如果将label设置为enabled状态,则label中的字体颜色会变灰,但shadow无影响: