简体   繁体   中英

UILabel attributed text not changing

I am having a problem updating the text on a UILabel . My ViewController changes its view property phoneNumberString . My view observes this property change and reacts, changing the label's attributed text. It observes using ReactiveCocoa.

[[RACAble(self.phoneNumberString) distinctUntilChanged]subscribeNext:^(id x) {
    NSString* s=(NSString*)x;
    UIFont* font=[UIFont systemFontOfSize:numbersFontSize weight:UIFontWeightThin];
    NSMutableDictionary* attributesDict=[NSMutableDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil];

    self.phoneNumberLabel.attributedText = [[NSAttributedString alloc]initWithString:s attributes:attributesDict];
    [self.phoneNumberLabel setNeedsDisplay];
    NSLog(@"label att text = %@\nlabel text = %@\ninput string = %@\n==",self.phoneNumberLabel.attributedText,self.phoneNumberLabel.text,x);
}];

It provides the following log:

label att text = +7 (225{
NSFont = "<UICTFont: 0x7a2942c0> font-family: \".SFUIDisplay-Thin\"; font-weight: normal; font-style: normal; font-size: 25.00pt";
}

label text = +7 (225
input string = +7 (225

I need attributed text to be located in my UILabel . The problem is that it provides no changes in the simulator. (Using native [self observeValueForKeyPath...] results in the same effect). I've solved this problem using notifications with the same code. But I have to use KVO.

Additional information:

  1. Here is my initialization code (before setting the observer):

      UILabel* phoneNumberLabel=[[UILabel alloc]init]; font=[UIFont systemFontOfSize:numbersFontSize weight:UIFontWeightThin]; attributesDict=[NSMutableDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil]; phoneNumberLabel.attributedText=[[NSAttributedString alloc]initWithString:@"+7 " attributes:attributesDict]; 
  2. Both methods run on the main thread.

  3. The UILabel 's frame is big enough to allocate.

If you have used size classes in .xib to set font of label then attributed text may not work. To work it properly remove size classes from .xib file

It looks like you are missing an assignment of the attribute to a range of the string. For example,

NSMutableAttributedString *attributedPhoneNumber = [[NSMutableAttributedString alloc] initWithString:x];
[attributedPhoneNumber addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [attributedPhoneNumber length])];
self.phoneNumberLabel.attributedText = attributedPhoneNumber;

Try calling your method in viewDidLayoutSubviews . For me it did the trick. I was doing it in viewDidLoad and it was an issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM