美文网首页iOS学习集--网上转载功能实现参考小知识
经常遇到的需要对UILabel处理的几个问题

经常遇到的需要对UILabel处理的几个问题

作者: SPIREJ | 来源:发表于2016-04-15 15:37 被阅读257次
  • 计算label中的字符所占宽和高
  • iOS7之后
- (CGSize)boundingRectWithSize:(CGSize)size text:(NSString *)text fount:(UIFont *)font 
{
    NSDictionary *attribute = @{NSFontAttributeName: font};
    CGSize retSize = [text boundingRectWithSize:size options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    return retSize;
}
  • iOS6
-(CGSize)sizeWithString:(NSString *)text size:(CGSize)size font:(UIFont)font
{
    CGSize size = [text sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];
    return size;
}
  • 设置Label中文字的行间距
+ (void)labelLineSpace:(UILabel *)label text:(NSString *)text Value:(CGFloat)value
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:value];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [text length])];
    label.attributedText = attributedString;
    [label sizeToFit];
}
  • Label的边框宽度粗细不一致处理
  • 如果设置了label.layer.border.width 为某一值,在不能的屏幕上显示的效果可能完全不一样,比如我之前做项目是设置了 border.width = 0.6,然后在6s上显示时粗细不一致,下面这方法可以解决这个问题。
CGFloat scale = [[UIScreen mainScreen] scale];
CGFloat width = scale > 0.0 ? 1.0 / scale : 1.0;
[self.layer setBorderWidth:width];

相关文章

网友评论

本文标题:经常遇到的需要对UILabel处理的几个问题

本文链接:https://www.haomeiwen.com/subject/hesnlttx.html