在对UIButton进行子类化时,UIControlState的名称是什么来获取值?

jdl*_*jdl 3 cocoa-touch objective-c

我是UIButton的子类.但我需要知道状态的按钮在绘制按钮的颜色向上或向下:

- (void)drawRect:(CGRect)rect{
     if (state==UIControlStateNormal) {
         //draw rect RED
     }
     if (state==UIControlEventTouchDown) 
         //draw rect BLUE
     }
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*l.s 5

你有没有尝试过查看文档?

  1. 转到UIButton参考
  2. 检查属性
  3. 什么都不明显
  4. 看看是否UIButton有一个超类
  5. 转到UIControl参考 - UIButton的超
  6. 检查属性
  7. 哦,看看有一处state房产

更新

接受的答案略有不正确,可能会导致一些令人烦恼的难以追踪的错误.

标题为UIControl声明state

@property(nonatomic,readonly) UIControlState state;                  // could be more than one state (e.g. disabled|selected). synthesized from other flags.
Run Code Online (Sandbox Code Playgroud)

现在抬头看看UIControlState我们看到的定义方式

enum {
    UIControlStateNormal       = 0,                       
    UIControlStateHighlighted  = 1 << 0,                  // used when UIControl isHighlighted is set
    UIControlStateDisabled     = 1 << 1,
    UIControlStateSelected     = 1 << 2,                  // flag usable by app (see below)
    UIControlStateApplication  = 0x00FF0000,              // additional flags available for application use
    UIControlStateReserved     = 0xFF000000               // flags reserved for internal framework use
};
typedef NSUInteger UIControlState;
Run Code Online (Sandbox Code Playgroud)

因此,当您处理位掩码时,您应该适当地检查状态,例如

if (self.state & UIControlStateNormal) { ... } 
Run Code Online (Sandbox Code Playgroud)

更新2

您可以通过绘制图像,然后将图像设置为背景来完成此操作,例如

- (void)clicked:(UIButton *)button;
{
    UIGraphicsBeginImageContext(button.frame.size);

    // Draw gradient

    UIImage *gradient = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    [button setBackgroundImage:image forState:UIControlStateNormal];
}
Run Code Online (Sandbox Code Playgroud)