我是objective c和iphone开发的新手。我很困惑。我试图创建在运行时创建的按钮,单击另一个按钮后,应用程序不知道它:
-(void)button4Pushed{
NSLog(@"Button 4 pushed\n");
Class cls = NSClassFromString(@"UIButton");//if exists {define class},else cls=nil
id pushButton5 = [[cls alloc] init];
CGRect rect =CGRectMake(20,220,280,30);
NSValue *rectValue = [NSValue valueWithCGRect:rect];
//--------------1st try set frame - work,but appears at wrong place
//[pushButton5 performSelector:@selector(setFrame:) withObject:rectValue];
//--------------2nd try set frame + this work correctly
[pushButton5 setFrame: CGRectMake(20,220,280,30)];
//this work correct [pushButton5 performSelector:@selector(setTitle:forState:) withObject:@"5th Button created by 4th" withObject:UIControlStateNormal];
//but i need to use invocation to pass different parameters:
NSMethodSignature *msignature;
NSInvocation *anInvocation;
msignature = [pushButton5 methodSignatureForSelector:@selector(setTitle:forState:)];
anInvocation = [NSInvocation invocationWithMethodSignature:msignature];
[anInvocation setTarget:pushButton5];
[anInvocation setSelector:@selector(setTitle:forState:)];
NSNumber* uicsn =[NSNumber numberWithUnsignedInt:UIControlStateNormal];
NSString *buttonTitle = @"5thbutton";
[anInvocation setArgument:&buttonTitle atIndex:2];
[anInvocation setArgument:&uicsn atIndex:3];
[anInvocation retainArguments];
[anInvocation invoke];
[self.view addSubview:(UIButton*)pushButton5];
}
我究竟做错了什么?调用被调用,但没有结果......我知道我可以这样创建它:
UIButton *pushButton3 = [[UIButton alloc] init];
[pushButton3 setFrame: CGRectMake(20, 140, 280, 30)];
[pushButton3 setTitle:@"I'm 3rd button!created by 2nd" forState:UIControlStateNormal];
[self.view addSubview:pushButton3];
但是我需要使用调用,不知道为什么它不起作用?
谢谢你的帮助。