Question

  • Say I have three UILabels.
  • I create a font and assign that font to all three labels.

Now I edit this font's type/size etc and expect the fonts of those labels to change too, which does not happen. I basically need to apply a single font to multiple labels and I know this can be done with an outlet collection but i'd just like some help in understanding the flaw in my logic here so here's my code...

self.labelFont = [UIFont fontWithName:@"System" size:12];

self.label1.font = self.labelFont;
self.label2.font = self.labelFont;
self.label3.font = self.labelFont;

self.labelFont = [UIFont fontWithName:@"Courier" size:30];

Thank

Was it helpful?

Solution

In your code you create two objects, [UIFont fontWithName:@"System" size:12], and [UIFont fontWithName:@"Courier" size:30].

Initially, your labelFont variable points to the first font object. Then you copy that pointer in the assignments to fonts of the three labels. At this moment, you have four pointers referencing the same object - namely, the object returned by the [UIFont fontWithName:@"System" size:12] call.

Illustration 1

Next, you change labelFont to point to [UIFont fontWithName:@"Courier" size:30]. Once you do that, the labelFont starts pointing to that new object; it no longer points to the old object. However, the three labels are still pointing to the old font, so their appearance does not change.

Illustration 2

OTHER TIPS

This can not be done immediately, you would require a pointer to pointer able to change the font of every label. But when a setter is called it triggers a method that may also cause some side effects, so the better way to do this is to create a setter to handle the behavior:

- (void) setLabelFont: (UIFont*) labelFont {
    _labelFont= labelFont;
    self.label1.font = self.label2.font = self.label3.font = labelFont;
}

You should just subclass Y UILabel, modify the font there and then any labels that you make part of the subclass will have your font. It is less coding and can save you headaches in the long term when you have 100+ labels you want to make the same font.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top