trouble with UIAppearance and UIButton subclassing

2019-08-23 03:56发布

I have a custom button, that is just a standard UIButton, but with a CAGradientLayer added in.

In my custom button, I have defined two properties:

@property (nonatomic, strong) UIColor* topColor UI_APPEARANCE_SELECTOR;
@property (nonatomic, strong) UIColor* bottomColor UI_APPEARANCE_SELECTOR;

If those two values get set, the my button draws itself with a nice linear gradient. Works great.

I also like to put as much into InterfaceBuilder as possible. So, on some of these buttons, in IB's "Identity Inpsector" I add in "User Defined Runtime Attributes" for these properties. Again, works great.

Next, I thought I'd try using UIAppearance proxies. Most of my custom gradient buttons all have the same colors. But there are a few that are different. So, I figured what I would do is use the appearance-proxy stuff to set the default colors for this class, and then for any buttons that are different, I could just set their values in IntefaceBuilder. This fails.

Apparently, what's happening is that it's reading the runtime attributes from my storyboard file first, but afterwards those values get overwritten by the appearance proxy. I wouldn't expect this to work this way, but it does.

Any tips on how to accomplish this? Or should I just give up on the runtime attributes thing?

1条回答
闹够了就滚
2楼-- · 2019-08-23 04:48

OK, I've thought about this, and I guess this is really what the Appearance proxy is supposed to do. So, my solution is to have two classes "MySpecialButton" and "MyAppearanceButton".

MyAppearanceButton will be a sub-class of MySpecialButton.

The look of "MyAppearanceButton" will be controlled by the appearance proxy calls. If I want a button that isn't controlled that way, I'll make a "MySpecialButton" and set the properties in the User Defined Runtime Attributes. That should do it.

查看更多
登录 后发表回答