创建UIlabel对象
UILabel* label = [[UILabel alloc] initWithFrame:self.view.bounds];
label.text = @"This is a UILabel Demo,";
label.font = [UIFont fontWithName:@"Arial" size:35];
label.textColor = [UIColor yellowColor];
label.textAlignment = UITextAlignmentCenter;
label.backgroundColor = [UIColor blueColor];
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;
[label sizeToFit];
CGSize size = [label.text sizeWithFont:label.font constrainedToSize:self.view.bounds.size lineBreakMode:label.lineBreakMode];CGRect rect = label.frame;
rect.size.height = size.height;
label.frame = rect;
typedef enum { UILineBreakModeWordWrap = 0, // 以空格为边界,保留整个单词 UILineBreakModeCharacterWrap, // 保留整个字符 UILineBreakModeClip, // 到边界为止 UILineBreakModeHeadTruncation, // 省略开始,以……代替 UILineBreakModeTailTruncation, // 省略结尾,以……代替 UILineBreakModeMiddleTruncation, // 省略中间,以……代替,多行时作用于最后一行 } UILineBreakMode;
技巧:根据字符串长度自动适应宽度和高度
//这个frame是初设的,没关系,后面还会重新设置其size。 UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,0,0)]; label.numberOfLines = 0; label.backgroundColor = [UIColor clearColor]; NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:20],}; NSString *str = @"abcdefg你上课可是你的拿到了"; CGSize textSize = [str boundingRectWithSize:CGSizeMake(100, 100) options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;; [label setFrame:CGRectMake(100, 100, textSize.width, textSize.height)]; label.textColor = [UIColor greenColor]; label.text = str; [self.view addSubview:label];
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。