效果如下:
ViewController.h
1 #import <UIKit/UIKit.h> 2 3 @interface ViewController : UIViewController 4 @property (strong, nonatomic) UILabel *lblMessage; 5 6 @end
ViewController.m
1 #import "ViewController.h" 2 3 @interface ViewController () 4 @end 5 6 @implementation ViewController 7 8 - (void)viewDidLoad { 9 [super viewDidLoad]; 10 11 self.title = @"Mutiline"; 12 self.view.backgroundColor = [UIColor blackColor]; 13 14 _lblMessage = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 320, 460)]; 15 _lblMessage.text = @"点击屏幕设置行数;在一个UILabel控件中显示多行文本"; 16 _lblMessage.textColor = [UIColor colorWithRed:0.335 green:0.915 blue:1.000 alpha:1.000]; 17 _lblMessage.textAlignment = NSTextAlignmentLeft; 18 _lblMessage.backgroundColor = [UIColor colorWithRed:0.852 green:0.941 blue:1.000 alpha:1.000]; 19 _lblMessage.adjustsFontSizeToFitWidth = NO; //默认值为NO 20 _lblMessage.baselineAdjustment = UIBaselineAdjustmentAlignBaselines; //baselineAdjustment属性只在adjustsFontSizeToFitWidth属性值设置为YES时才有效;默认值为UIBaselineAdjustmentAlignBaselines 21 _lblMessage.numberOfLines = 1; //默认值为1;如果要自适应行数就设置值为0 22 [self.view addSubview:_lblMessage]; 23 } 24 25 - (void)didReceiveMemoryWarning { 26 [super didReceiveMemoryWarning]; 27 // Dispose of any resources that can be recreated. 28 } 29 30 #pragma mark - Private Methods 31 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 32 static int i = 1; 33 NSString *message = @"_lblMessage.numberOfLines = %d;点击屏幕设置行数;在一个UILabel控件中显示多行文本。 34 点击屏幕设置行数;在一个UILabel控件中显示多行文本。 35 点击屏幕设置行数;在一个UILabel控件中显示多行文本。 36 点击屏幕设置行数;在一个UILabel控件中显示多行文本。 37 点击屏幕设置行数;在一个UILabel控件中显示多行文本。"; 38 _lblMessage.numberOfLines = (i + 1) % 4; 39 _lblMessage.text = [NSString stringWithFormat:message, _lblMessage.numberOfLines]; 40 i++; 41 } 42 43 @end
时间: 2024-12-18 18:14:37