自定义UIButton的setIsSelected方法未被称为

时间:2015-05-25 04:16:29

标签: ios objective-c uibutton

我有一个基于UIButton的自定义类,我在这个自定义类中调用自定义setter方法时遇到了困难。我将在这些文件中列出代码:

  1. CallMyMethod.h(UIButton的子类)
  2. CallMyMethod.m
  3. CallOtherClassMethod.h(在CallMyMethod中调用setter方法)
  4. CallOtherClassMethod.m
  5. CallMyMethod.h

    @interface CallMyMethod : UIButton
    
    @property (nonatomic, setter=setIsSelected:) BOOL isSelected;
    @property (nonatomic, retain) UIImageView *checkmarkImageView;
    
    - (void)setIsSelected:(BOOL)aIsSelected; //this is unnecessary, I guess
    
    @end
    

    CallMyMethod.m

    @implementation CallMyMethod
    
    @synthesize isSelected = _isSelected;
    @synthesize checkmarkImageView = _checkmarkImageView;
    
    - (id)initWithFrame:(CGRect)frame
    {
      self = [super initWithFrame:frame];
      if (self) {
        // Initialization code
        [self loadView];
      }
      return self;
    }
    
    - (void) loadView
    {
      [self.checkmarkImageView setHidden:YES];
    }
    
    - (UIImageView *)checkmarkImageView
    {
        if (_checkmarkImageView == nil) {
    
          UIImage *checkmarkImage = [UIImage imageNamed:@"checkmark.png"];
    
          _checkmarkImageView = [[UIImageView alloc]initWithImage:checkmarkImage];
    
          [_checkmarkImageView setFrame:CGRectMake(10, 10, 32, 32)];
    
          [self addSubview:_checkmarkImageView];
      }
    
      return _checkmarkImageView;
    }
    
    - (void)setIsSelected:(BOOL)aIsSelected
    {
      _isSelected = aIsSelected;
    
      [self.checkmarkImageView setHidden:!_isSelected];
      [self addSubview:_checkmarkImageView];
    
    }
    
    @end
    

    CallOtherClassMethod.h

    @class CallMyMethod;    
    
    @interface CallOtherClassMethod : UIViewController
    
    @property (nonatomic,retain) CallMyMethod *btnCMM;
    
    @end
    

    CallOtherClassMethod.m

    #import "CallMyMethod.h"
    
    @implementation CallOtherClassMethod
    
    @synthesize btnCMM;
    
    - (void)viewDidLoad
    {
      [super viewDidLoad];
      self.btnCMM = [[CallMyMethod alloc]initWithFrame:CGRectMake(0, 30, 50, 70)];
    
      //somewhere in my code I will add btnCMM to the view
      [someView bringSubviewToFront: btnCMM];
      [someView addSubview: btnCMM];
    
    }
    
    //somewhere where I pressed a button to trigger this method
    - (IBAction) pressMe:(id)sender
    {
      NSLog(@"self.btnCMM %@", self.btnCMM); //returned as btnCMM is nil ?!
      [self.btnCMM setIsSelected:YES];
    }
    
    @end
    

    问题在于程序无法在setIsSelected方法中运行代码,我已经在NSLog中跟踪btnCMM为nil。我想知道为什么会这样,因为当我将CallOtherClassMethod称为UIViewController时,viewDidLoad会初始化我的自定义按钮。我在这里做错了吗?

1 个答案:

答案 0 :(得分:0)

为什么不覆盖setSelected,这是UIButton上的一个方法,然后使用button.selected = YES

如果你想调试你的按钮变为零的原因,在你的UIButton子类中实现dealloc,在那里放一个断点,并查看堆栈跟踪以找到原因。