是的,这是一件非常常见的事情。我创建了自己的班级来处理这种情况。 这个类叫做ControlGroup,唯一的责任是跟踪你添加到它的所有UIControls,并且只选择其中的一个。控件(在你的情况下是UIButton)不需要知道任何关于对方的信息,你可以拥有任意数量的控件。当你完成它们的时候,不要忘记删除控件,因为这个类将保留它的元素。
这就是:
的* .h文件中:
// This is a very simple class whose only purpose in life is to manage a group of
// UIControls in a way that only one of them is selected at any one time
@interface ControlGroup : NSObject
-(void)addControl:(UIControl*)control;
-(void)removeControl:(UIControl*)control;
-(UIControl*)currentlySelectedControl;
@end
的* .m文件:
#import "ControlGroup.h"
@interface ControlGroup()
@property (nonatomic, strong) NSMutableSet *controls;
@end
@implementation ControlGroup
@synthesize controls = _controls;
-(id)init {
if ((self = [super init])) {
_controls = [[NSMutableSet alloc] init];
}
return self;
}
-(void)addControl:(UIControl*)control {
if (![self.controls containsObject:control]) {
[self.controls addObject:control];
[control addTarget:self action:@selector(controlTouched:) forControlEvents:UIControlEventTouchUpInside];
}
}
-(void)removeControl:(UIControl *)control {
if ([self.controls containsObject:control]) {
[control removeTarget:self action:@selector(controlTouched:) forControlEvents:UIControlEventTouchUpInside];
[self.controls removeObject:control];
}
}
-(void)controlTouched:(id)sender {
if ([sender isKindOfClass:[UIControl class]]) {
UIControl *selectedControl = (UIControl*)sender;
for (UIControl *control in self.controls) {
[control setSelected:FALSE];
}
[selectedControl setSelected:TRUE];
}
}
-(UIControl*)currentlySelectedControl {
UIControl *selectedControl = nil;
for (UIControl *control in self.controls) {
if ([control isSelected]) {
selectedControl = control;
break;
}
}
return selectedControl;
}
-(NSString*)description {
return [NSString stringWithFormat:@"ControlGroup; no. of elements: %d, elements: %@\n", self.controls.count, self.controls];
}
@end
希望这有助于!
编辑:如何使用这个类
你必须做的第一件事是导入你要去的地方使用它。在你的情况下,它会在您创建按钮类:
1)导入类#import "ControlGroup.h"
然后,你必须申报财产,以保持较强的参考吧
2)在您的* .h文件中添加以下内容:@property (nonatomic, strong) ControlGroup *controlGroup;
之后,在你的init方法,你必须创建对象:
3)添加这是你的init方法中:_controlGroup = [[ControlGroup alloc] init];
现在您对可以使用的ControlGroup对象有强烈的参考。下一步你需要做的是创建你的按钮。我相信你已经有了这一步。
4)创建你的按钮。在创建和配置按钮时,请使用UIButton
的方法setImage:forState
,并为UIControlStateNormal
状态设置一个图像,并为UIControlStateSelected
状态设置另一个图像。
最后,对于您创建的每个按钮,都必须将其添加到您拥有的controlGroup
对象。
5)每个按钮添加到ControlGroup对象:[self.controlGroup addControl:myButton];
尝试这些步骤,让我知道如何去为您服务。
我真的很抱歉,我是新的ios,所以你能帮我整合吗?你有没有关于它的例子?谢谢 –
@ TwentyThr23当然,让我更新我的答案 – LuisCien
好的非常感谢你 –