我正在尝试实现切换按钮的自定义实现,以便一次只能选择一个。我遇到了一个奇怪的错误,我使用[[ajdSwitchButton alloc] init]
. 在初始化中,我设置了一个类属性,如下所示self.currentSelection = 2
。
问题是在init
第一次调用和第一次调用IBAction
方法之间,值更改为 0。我不知道为什么。以下是相关代码:
ajdSwitchButton.h
#import <UIKit/UIKit.h>
@interface ajdSwitchButton : UIView
@property (nonatomic) NSInteger currentSelection;
// Button Outlets
@property (nonatomic, strong) IBOutlet UIButton *buttonOne;
@property (nonatomic, strong) IBOutlet UIButton *buttonTwo;
// Button Actions
- (IBAction)buttonPress:(id)sender;
- (IBAction)buttonPressTwo:(id)sender;
// Instance Methods
- (void)switchButtonState:(UIButton *)button;
@end
ajdSwitchButton.m
#import "ajdSwitchButton.h"
@implementation ajdSwitchButton
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
_currentSelection = 2;
}
return self;
}
// Handles button press actions for buttonOne
- (IBAction)buttonPress:(id)sender {
NSLog(@"%@", self);
// Y button pressed
if (self.currentSelection == 2) {
// No button is selected
// Highlight and select buttonOne
[self performSelector:@selector(switchButtonState:) withObject:self.buttonOne afterDelay:0.0];
} else if (self.currentSelection == 1) {
// No was previously selected
// Unselect NO and select YES
[self performSelector:@selector(switchButtonState:) withObject:self.buttonTwo afterDelay:0.0];
[self performSelector:@selector(switchButtonState:) withObject:self.buttonOne afterDelay:0.0];
} else {
// Y button already pressed
[self performSelector:@selector(switchButtonState:) withObject:self.buttonOne afterDelay:0.0];
}
self.currentSelection = 0;
}
- (IBAction)buttonPressTwo:(id)sender {
// N button pressed
NSLog(@"%i", self.currentSelection);
if (self.currentSelection == 2) {
// No button is selected
// Highlight and select buttonOne
[self performSelector:@selector(switchButtonState:) withObject:self.buttonTwo afterDelay:0.0];
} else if (self.currentSelection == 0) {
// Yes was previously selected
// Unselect YES and select NO
[self performSelector:@selector(switchButtonState:) withObject:self.buttonTwo afterDelay:0.0];
[self performSelector:@selector(switchButtonState:) withObject:self.buttonOne afterDelay:0.0];
} else {
// N button already pressed
[self performSelector:@selector(switchButtonState:) withObject:self.buttonTwo afterDelay:0.0];
}
self.currentSelection = 1;
}
// Switches the look and state of the button
- (void)switchButtonState:(UIButton *)button {
if (!button.selected) {
button.highlighted = YES;
button.selected = YES;
} else {
button.highlighted = NO;
button.selected = NO;
}
}
@end
我将的实例链接ajdSwitchButton
到. 任何帮助将不胜感激。IBOutlet
ViewController
init
编辑:我粘贴了一些 NSLogs 以在调用该IBAction
方法后直接检查对象的内存值。这是之前和之后:
<ajdSwitchButton: 0x746d2e0; frame = (0 0; 0 0); layer = <CALayer: 0x7472c40>>
<ajdSwitchButton: 0x7471b10; frame = (77 232; 180 83); autoresize = TM+BM; layer = <CALayer: 0x7471bf0>>