UILabel开发中遇到的好用的

根据文字计算UILabel的size

- (CGSize)sizeWithAttributes:(nullable NSDictionary *)attires

例子:

 // 获取文本
    NSString *string = @"ScofieldTang文字滚动ScofieldTang文字滚动ScofieldTang文字滚动";
    // 初始化label
    UILabel *label      = [UILabel new];
    label.text          = string;
    label.font          = [UIFont systemFontOfSize:16];
    
    // 计算尺寸[label.text sizeWithFont:label.font];//已抛弃
    CGSize size         = [label.text  sizeWithAttributes:@{NSFontAttributeName : label.font}];
    label.frame         = (CGRect){CGPointZero, size};

UILabel位子滚动播放(跑马灯)

// 获取文本
    NSString *string = @"ScofieldTang文字滚动ScofieldTang文字滚动ScofieldTang文字滚动";
    
    // 初始化label
    UILabel *label      = [UILabel new];
    label.text          = string;
    label.font          = [UIFont systemFontOfSize:16];
    
    // 计算尺寸[label.text sizeWithFont:label.font];//已抛弃
    CGSize size         = [label.text  sizeWithAttributes:@{NSFontAttributeName : label.font}];

    label.frame         = (CGRect){CGPointZero, size};
    
    UIScrollView *showView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenW * 0.3, 44)];
    
    showView.contentSize   = size;
    showView.showsHorizontalScrollIndicator = NO;
    [showView addSubview:label];
    //[self.view addSubview:showView];
    self.navigationItem.titleView = showView;
    // 动画 判断文字宽度大于scrollView宽度时开启动画
    if (size.width > showView.frame.size.width) {
        [UIView animateKeyframesWithDuration:5
                                       delay:0
                                     options:UIViewAnimationOptionRepeat //动画重复的主开关
         |UIViewAnimationOptionAutoreverse //动画重复自动反向,需要和上面这个一起用
         |UIViewAnimationOptionCurveLinear //动画的时间曲线,滚动字幕线性比较合理
                                  animations:^{
                                      // 计算移动的距离
                                      CGPoint point = showView.contentOffset;
                                      point.x = size.width - 200;
                                      showView.contentOffset = point;
                                  }
                                  completion:^(BOOL finished) {
                                      
                                  }];
    }

你可能感兴趣的:(UILabel开发中遇到的好用的)