0

私は次のようなボタンを作成しました:

UIButton *toTop = [UIButton buttonWithType:UIButtonTypeCustom];
toTop.frame = CGRectMake(12, 12, 37, 38);
toTop.tintColor = [UIColor clearColor];
[toTop setBackgroundImage:[UIImage imageNamed:@"toTop.png"] forState:UIControlStateNormal];
[toTop addTarget:self action:@selector(scrollToTop:) forControlEvents:UIControlEventTouchUpInside];

この同じボタンを何度も繰り返し使用したいさまざまなUIViewがありますが、それはできません。UIButton同じものを複数のビューに追加しようとしましたが、最後に追加した場所に常に表示されます。私も試しました:

UIButton *toTop2 = [[UIButton alloc] init];
toTop2 = toTop;

これは機能しません。この同じボタンに同じプロパティを何度も設定せずにこれを行う効率的な方法はありますか?ありがとう。

4

1 に答える 1

2

UIViewsは単一のスーパービューしか持てません。2番目のアプローチでは、ボタンを割り当て、それを破棄して、最初のボタンを指すようにポインターを割り当てるだけです。つまりtoToptoTop2両方がまったく同じボタンインスタンスを指しているので、単一のスーパービューの制限に戻ります。

UIButtonしたがって、これを実現するには、個別のインスタンスを作成する必要があります。コードを複製せずにこれを行う1つの方法は、カテゴリを作成することです。このようなものが機能するはずです:

UIButton + ToTopAdditions.h:

@interface UIButton (ToTopAdditions)

+ (UIButton *)toTopButtonWithTarget:(id)target;

@end

UIButton + ToTopAdditions.m:

@implementation UIButton (ToTopAdditions)

+ (UIButton *)toTopButtonWithTarget:(id)target
{
    UIButton *toTop = [UIButton buttonWithType:UIButtonTypeCustom];
    toTop.frame = CGRectMake(12, 12, 37, 38);
    toTop.tintColor = [UIColor clearColor];
    [toTop setBackgroundImage:[UIImage imageNamed:@"toTop.png"] forState:UIControlStateNormal];
    [toTop addTarget:target action:@selector(scrollToTop:) forControlEvents:UIControlEventTouchUpInside];
    return toTop;
}

@end

インポートUIButton+ToTopAdditions.hし、適切なターゲットをメソッドに渡します(あなたの場合はそのように聞こえselfます)。そうすれば、必要な数の同じボタンを取得できます。お役に立てれば!

于 2012-09-29T00:21:35.417 に答える