May*_*sse 28 cocoa-touch objective-c uicontrol ios
有没有办法为a设置自定义状态 - 不是现有UIControlState值之一UIControl?
在UIControlSate枚举中,有16位可用于自定义控件状态:
UIControlStateApplication = 0x00FF0000, // additional flags available for application use
Run Code Online (Sandbox Code Playgroud)
问题是,UIControl的state属性是只读的.
我想为我UIButton的自定义状态设置不同的背景图像.
Nic*_*eet 36
您可以在UIControl的子类中使用自定义状态.
customState,您将在其中管理自定义状态. [self stateWasUpdated].state属性以[super state]针对您的方式按位返回ORcustomStateenabled,selected并highlighted制定者,让他们打电话[self stateWasUpdated].这将允许您响应状态的任何更改,而不仅仅是更改customState stateWasUpdated用逻辑实现以响应状态的变化在标题中:
#define kUIControlStateCustomState (1 << 16)
@interface MyControl : UIControl {
UIControlState customState;
}
Run Code Online (Sandbox Code Playgroud)
在实施中:
@implementation MyControl
-(void)setCustomState {
customState |= kUIControlStateCustomState;
[self stateWasUpdated];
}
-(void)unsetCustomState {
customState &= ~kUIControlStateCustomState;
[self stateWasUpdated];
}
- (UIControlState)state {
return [super state] | customState;
}
- (void)setSelected:(BOOL)newSelected {
[super setSelected:newSelected];
[self stateWasUpdated];
}
- (void)setHighlighted:(BOOL)newHighlighted {
[super setHighlighted:newHighlighted];
[self stateWasUpdated];
}
- (void)setEnabled:(BOOL)newEnabled {
[super setEnabled:newEnabled];
[self stateWasUpdated];
}
- (void)stateWasUpdated {
// Add your custom code here to respond to the change in state
}
@end
Run Code Online (Sandbox Code Playgroud)
根据@Nick的回答,我实现了一个更简单的版本.此子类公开一个BOOL outlined与函数类似的属性selected,highlighted和enabled.
在[customButtton setImage:[UIImage imageNamed:@"MyOutlinedButton.png"] forState:UIControlStateOutlined]更新outlined属性时,做一些事情会使它自动运行.
如果需要,可以添加更多这些州+财产.
UICustomButton.h
extern const UIControlState UIControlStateOutlined;
@interface UICustomButton : UIButton
@property (nonatomic) BOOL outlined;
@end
Run Code Online (Sandbox Code Playgroud)
UICustomButton.m
const UIControlState UIControlStateOutlined = (1 << 16);
@interface OEButton ()
@property UIControlState customState;
@end
@implementation OEButton
- (void)setOutlined:(BOOL)outlined
{
if (outlined)
{
self.customState |= UIControlStateOutlined;
}
else
{
self.customState &= ~UIControlStateOutlined;
}
[self stateWasUpdated];
}
- (BOOL)outlined
{
return ( self.customState & UIControlStateOutlined ) == UIControlStateOutlined;
}
- (UIControlState)state {
return [super state] | self.customState;
}
- (void)stateWasUpdated
{
[self setNeedsLayout];
}
// These are only needed if you have additional code on -(void)stateWasUpdated
// - (void)setSelected:(BOOL)newSelected
// {
// [super setSelected:newSelected];
// [self stateWasUpdated];
// }
//
// - (void)setHighlighted:(BOOL)newHighlighted
// {
// [super setHighlighted:newHighlighted];
// [self stateWasUpdated];
// }
//
// - (void)setEnabled:(BOOL)newEnabled
// {
// [super setEnabled:newEnabled];
// [self stateWasUpdated];
// }
@end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8952 次 |
| 最近记录: |