IBOutletCollection (UIbutton)

风格不统一 提交于 2019-12-12 02:52:10

问题


in my .h I have

IBOutlet NSMutableArray *buttons;
@property (nonatomic, retain) IBOutletCollection(UIButton) NSMutableArray *buttons;
-(void)play:(UIButton *)theButton;

in my .m I have

-(void)initButtons{
buttons = [[NSMutableArray alloc] initWithCapacity:1];
UIButton *myBut = [UIButton alloc];
[buttons addObject: myBut];
[[buttons objectAtIndex:0] addtarget:self action@selector(play:) forControlEventTouchUpInside];
}

...

-(void)dealloc{
[buttons dealloc];
[super deallloc];
}

.....

-(void)viewDidLoad{
[super viewDidLoad];
[self initButtons];
}

I dragged the buttons IBoutletCollection in interface builder to a simple button, but when I test it it doesn't perform the expected action;

I should mention that if I turn my action into (IBAction) instead of (void) and link it to the button it works;

I don't understand very well NSArrays and outlet collections.


回答1:


The array is set for you with whatever buttons you've connected to the collection in the NIB. It fails to do anything because you've reset the ivar here:

buttons = [[NSMutableArray alloc] initWithCapacity:1];

…or because you've not connected buttons to the collection.




回答2:


You don't need outlets to connect buttons to methods.

Get rid of all your outlet and property and initButtons code and just have this:

//in .h

-(IBAction)play:(UIButton *)theButton;

//in .m

-(IBAction)play:(UIButton *)theButton
{
    //the code for your play action
}

Then in Interface Builder, ctrl-drag from the button to the File's Owner and select the play: action.




回答3:


Declare your UIButton myBut as an IBOutlet with property in .h file.connect your button outlet in xib to myBut.No need to declare NSMutableArray as an IBOutletCollection or IBOutlet.You simply declare it and No need to allocate myBut again inside initButtons method.

You can do like this.

viewController.h

@property (strong, nonatomic) IBOutlet UIButton *myButton;
@property (nonatomic,strong) NSMutableArray *buttons;
-(void)initButtons;
-(void)play:(id)sender;

inSide xib connect your button outlet to myButton

viewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initButtons];
    // Do any additional setup after loading the view, typically from a nib.
}


-(void)initButtons{
    buttons = [[NSMutableArray alloc] initWithCapacity:1];
    [buttons addObject: myButton];
    [[buttons objectAtIndex:0] addTarget:self action:@selector(play:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)play:(id)sender
{
    NSLog(@"button tapped");
}


来源:https://stackoverflow.com/questions/9159567/iboutletcollection-uibutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!