【问题标题】:Subclass simple UIButton to checkbox将简单的 UIButton 子类化为复选框
【发布时间】:2013-04-08 06:48:57
【问题描述】:

我正在继承 UIButton 以创建一个简单的复选框行为。这是代码:

#import "RadioButton.h"

@implementation RadioButton
@synthesize isSelected;

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
[self ChangeButtonState];
 }

  -(void)ChangeButtonState{
  if (!isSelected) {
    isSelected = YES;
    [self setBackgroundImage:[UIImage imageNamed:@"radiobtn_on.png"]      forState:UIControlStateNormal];
    }
    else{
    isSelected = NO;
    [self setBackgroundImage:[UIImage imageNamed:@"radiobtn_off.png"] forState:UIControlStateNormal];
     }
     }

    -(id)init{
     self.adjustsImageWhenHighlighted=YES;
    self.alpha = 1;
     [self ChangeButtonState];
    isSelected = NO;
    [self setBackgroundImage:[UIImage imageNamed:@"radiobtn_off.png"] forState:UIControlStateNormal];
return self;
    }

    - (id)initWithFrame:(CGRect)frame
     {

    [self setBackgroundImage:[UIImage imageNamed:@"radiobtn_off.png"] forState:UIControlStateNormal];
    isSelected = NO;
    self = [super initWithFrame:frame];
    if (self) {
    // Initialization code
     }
     return self;
      }

    /*
  // Only  override drawRect: if you perform custom drawing.
   // An empty implementation adversely affects performance during animation.
     - (void)drawRect:(CGRect)rect
    {
       // Drawing code
     }
     */

     @end

首先,当我在启动应用程序时将界面构建器中的类设置为一个按钮时,我什么都看不到,直到我点击这个不可见的按钮。

第二件事是图像看起来比原始图像暗

帮助会很棒! 谢谢!

【问题讨论】:

    标签: iphone ios uibutton uikit


    【解决方案1】:

    在 - (void)awakeFromNib 中尝试你的东西。在您的子类中定义此方法。当您在 xib 中分配自定义类时,将调用此方法并在此处应用您的逻辑。

    【讨论】:

    • 第一个问题现在可以了,按下之前加载的图像正常,当我按下按钮时它变得更暗。
    • 你做错了 - (id)initWithFrame:(CGRect)frame { [self setBackgroundImage:[UIImage imageNamed:@"radiobtn_off.png"] forState:UIControlStateNormal]; isSelected = 否; self = [super initWithFrame:frame]; if (self) { // 初始化代码 } return self;总是你必须在初始化 self bcz 后做你的事情,它可能会返回 nil。
    • 得到它,代码从笔尖移动到唤醒状态。但是这种“黑暗”仍然会发生
    • 当然,它看起来更像是突出显示的东西
    • 使用 setImage 代替 setBackgroundImage: bcz 它会拉伸你的图像
    猜你喜欢
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    • 1970-01-01
    相关资源
    最近更新 更多