Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I *replace* the UILabel on a UIButton with FXLabel?

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.

like image 913
Dylan Gattey Avatar asked Dec 21 '11 06:12

Dylan Gattey


2 Answers

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!

like image 182
sudo rm -rf Avatar answered Oct 19 '22 22:10

sudo rm -rf


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.

like image 24
XJones Avatar answered Oct 19 '22 23:10

XJones