由于方法多种多样,这里介绍笔者常用的一种设置方法,比较简单格式较固定,故闲话不多说,直接上代码:
UILabel *headerLabel = [UILabel new];
headerLabel.font = [UIFont systemFontOfSize:15];
NSString *titleContent = @"月光如流水一般,静静地泻在这一片叶子和花上。薄薄的青雾浮起在荷塘里。叶子和花仿佛在牛乳中洗过一样;又像笼着轻纱的梦。虽然是满月,天上却有一层淡淡的云,所以不能朗照;但我以为这恰是到了好处——酣眠固不可少,小睡也别有风味的。月光是隔了树照过来的,高处丛生的灌木,落下参差的斑驳的黑影,峭楞楞如鬼一般;弯弯的杨柳的稀疏的倩影,却又像是画在荷叶上。塘中的月色并不均匀;但光与影有着和谐的旋律,如梵婀玲上奏着的名曲。";
headerLabel.text = titleContent;
headerLabel.numberOfLines = 0;//多行显示,计算高度
CGSize titleSize = [titleContent boundingRectWithSize:CGSizeMake(kScreenWidth * 0.8, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13]} context:nil].size;
// 调整行间距
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:titleContent];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:10];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [titleContent length])];
headerLabel.attributedText = attributedString;
[headerLabel sizeToFit];
[headerLabel setFrame:CGRectMake((kScreenWidth - titleSize.width) * 0.5,(kScreenHeight - titleSize.height) * 0.5 , titleSize.width, titleSize.height)];
[self.view addSubview:headerLabel];