首页 > 代码库 > UILabel顶端对齐
UILabel顶端对齐
比较一劳永逸的写法是对label添加一个分类
@interface UILabel (VerticalAlign)/** 顶端对齐 */-(void)alignTop;/** 底部对齐 */-(void)alignBottom;@end
-(void)alignTop{ CGSize fontSize = [self.text sizeWithAttributes:@{NSFontAttributeName:self.font}]; double finalHeight = fontSize.height * self.numberOfLines; double finalWidth = self.frame.size.width; CGSize theStringSize = [self.text boundingRectWithSize:CGSizeMake(finalWidth, finalHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.font} context:nil].size; int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height; for(int i=0; i<newLinesToPad; i++){ self.text = [self.text stringByAppendingString:@"\n "]; }}
-(void)alignBottom{ CGSize fontSize = [self.text sizeWithAttributes:@{NSFontAttributeName:self.font}]; double finalHeight = fontSize.height * self.numberOfLines; double finalWidth = self.frame.size.width; CGSize theStringSize = [self.text boundingRectWithSize:CGSizeMake(finalWidth, finalHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.font} context:nil].size; int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height; for(int i=0; i<newLinesToPad; i++){ self.text = [NSString stringWithFormat:@" \n%@",self.text]; }}
然后在使用时添加[myLabel alignTop]即可。
添加前
使用后
UILabel顶端对齐
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。