UIButton的titleLabe setAttributeSting 首次不起作用

环境xcode7.3 ios9.3 真机模拟器均出现 UIButton的titleLabe setAttributeSting 首次不起作用,之后每一次 都正常,百思不得解,无奈之下改变策略,讲button title设置空,就是不设置title,另外加一个Label 把要设置 attributeString 设置在单独label 上,再加Btn aad 在label上,Button 与 Label 大小相等。完美解决button titleLabel setAttributeSting首次不起作用的问题.

code 如下:

#pragma mark 显示最近地铁站路线
- (void)showWayToStationWithStation:(SubwayStationModel *)station from:(CLLocationCoordinate2D) coordinate distance:(double)distance{
    _wayLabel.frame = CGRectMake(0, SCREEN_HEIGHT-49-64, SCREEN_WIDTH, 80);
    NSString *title = [NSString stringWithFormat:@"距离最近的地铁站
%@ %ld米
查看步行线路",station.stationName,(long)distance];
    
    [_wayLabel setText:title];
    
    NSString *string = title;
    NSRange rangeLeft = [title rangeOfString:@"距离最近的地铁站"];
    NSRange rangeRight = [title rangeOfString:@"查看步行线路"];
    NSRange rangeCenter = NSMakeRange(rangeLeft.length, rangeRight.location - rangeLeft.length);
    NSRange rangeAll = NSMakeRange(0, title.length);
    
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:string];
    
    [attributeStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0.087 green:0.024 blue:0.023 alpha:1.000] range:rangeLeft];
    [attributeStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:1.000 green:0.288 blue:0.268 alpha:1.000] range:rangeCenter];
    [attributeStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0.043 green:0.431 blue:0.046 alpha:1.000] range:rangeRight];
    [attributeStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:rangeCenter];
    [attributeStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:rangeRight];
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 2.5;
    style.alignment = NSTextAlignmentCenter;
    [attributeStr addAttribute:NSParagraphStyleAttributeName value:style range:rangeAll];
    [_wayLabel setAttributedText:attributeStr];
    
    [UIView animateWithDuration:0.35 animations:^{
        _wayLabel.mkY -= 80;
    } completion:^(BOOL finished) {
        [self performSelector:@selector(hiddenShowWayView) withObject:nil afterDelay:3];
    }];

}

- (void)hiddenShowWayView{
    [UIView animateWithDuration:0.35 animations:^{
        _wayLabel.mkY += 80;
    } completion:^(BOOL finished) {
        
    }];
}
原文地址:https://www.cnblogs.com/zhujin/p/5632010.html