8

So, I'm trying to change the UILabel on a UIButton to an instance of an FXLabel instead. Check out the link for more on FXLabel (https://github.com/nicklockwood/FXLabel). I know by using class extensions (Subclass UIButton to add a property), I could always add another property, in my case, an FXLabel by just adding a subview basically. However, I like the convenience and features of the titleLabel property already present.

Is there some method to "switch" the UILabel for an FXLabel by subclass or category?

I do know I could do this, but it's such a hack and isn't future proof. And I don't know how to then change the class type (Get UILabel out of UIButton).

UILabel *label;
for (NSObject *view in button.subviews) {
    if ([view isKindOfClass:[UILabel class]]) {
        label = (UILabel *)view;
        break;
    }
}

Thoughts?? Thanks.

Community
  • 1
  • 1
Dylan Gattey
  • 1,713
  • 13
  • 34

2 Answers2

6

Here's another way you could at least access the label. Create a subclass of UIButton, and in that subclass override layoutSubviews. From there you can access the label directly:

- (void)layoutSubviews {
    [super layoutSubviews];

    UILabel *titleLabel = [self titleLabel];
}

Now we're still stuck with the problem of changing that label to be a subclass. I guess you could try to dynamically swap the UILabel's class with your FXLabel subclass (as detailed here), but to be honest that's pretty risky.

I'd say you're better off just creating your own UIControl that you can customize to your hearts content. No risk, just pure goodness. It shouldn't be too hard to imitate a simple UIButton. Good luck!

sudo rm -rf
  • 29,408
  • 19
  • 102
  • 161
  • Thanks for the tip. I think I'll just try creating my own custom class. I'll mark this as answering my question if no one else gives me anything better. Thanks! – Dylan Gattey Dec 21 '11 at 08:05
  • 1
    I just hacked it and added the label on top of the button without actually setting text on the button. Now I have to keep track of two properties for alpha changes, etc, but it's much easier than trying to create my own UIControl. I'll work on it in the future and see if I get anything – Dylan Gattey Dec 23 '11 at 22:35
1

Sorry to say it but I don't think you can do this in any reliable way. Even if you subclassed UIButton and overrode the titleLabel methods you'd also have to handle the state settings. And you never know when the internal code refers directly to a private ivar for the label.

I created a subclass of UIButton for my apps to do something similar (custom button layouts & subviews), sorry I can't share it right now, it's owned by a client. It's not too difficult to create your own state handling code for your own subviews.

XJones
  • 21,959
  • 10
  • 67
  • 82