1

私は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];

しかし、呼び出しを使用する必要がありますが、なぜ機能しないのですか?

ご協力いただきありがとうございます。

4

2 に答える 2

2

2 番目の引数として NSNumber * を設定しますが、(効果的に) 呼び出そうとしているメソッドには int が必要です。まったく同じコードを使用しますが、代わりに次の行を試してください。

UIControlState uicsn = UIControlStateNormal;

// それから

[anInvocation setArgument:&uicsn atIndex:3];
于 2011-08-10T12:52:42.047 に答える
1

なぜ呼び出しを使用する必要があるのですか?

更新: ユースケースに基づいて、他のクラスを制御しない限り、代わりにこの署名に一致するメソッドを持つプロトコルを使用し、これを呼び出すことが合法であるオブジェクトを収集します。

NSInvocationランタイム ビルディング ブロック/最終手段クラスです。周囲のオブジェクトをまったく制御できる場合は、プロトコル (オブジェクトにメソッドがある場合) やブロックまたは関数ポインター (具体化されていない機能が必要な場合) など、利用可能な他のツールを使用することになっています。

知覚の答えは技術的な問題を解決しますが、あなたは物事をもっと複雑にしているかもしれません.

于 2011-08-10T11:50:17.523 に答える