ジェイコブは、カテゴリ メソッドがサブクラス メソッドとは異なる動作をすることを強調しています。Apple は、完全に新しいカテゴリ メソッドのみを提供することを強くお勧めします。これは、そうしないとうまくいかないことが複数あるためです。その 1 つは、カテゴリ メソッドを定義すると、同じ名前のメソッドの他の既存の実装が基本的にすべて消去されることです。
残念ながら、あなたがやろうとしていることは、UIButton
サブクラス化を避けるように特別に設計されているようです。a のインスタンスを取得する唯一の認可された方法UIButton
は、コンストラクターを使用すること[UIButton buttonWithType:]
です。Jacobのようなサブクラスの問題は(このように)示唆しています:
@implementation MyCustomButton
+ (id)buttonWithType:(UIButtonType)buttonType {
return [super buttonWithType:buttonType]; //super here refers to UIButton
}
@end
によって返される型はではなく[MyCustomButton buttonWithType:]
のままであるということです。Apple はinit メソッドを提供していないため、サブクラスがそれ自体をインスタンス化し、.UIButton
MyCustomButton
UIButton
UIButton
カスタマイズされた動作が必要な場合UIView
は、ボタンを常にサブビューとして含むカスタム サブクラスを作成して、 の機能の一部を活用できUIButton
ます。
このようなもの:
@interface MyButton : UIView {}
- (void)buttonTapped;
@end
@implementation MyButton
-(id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = self.bounds;
[button addTarget:self action:@selector(buttonTapped)
forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
}
return self;
}
- (void)buttonTapped {
// Respond to a button tap.
}
@end
より複雑なユーザー インタラクションに応じてボタンにさまざまな動作をさせたい場合は、[UIButton addTarget:action:forControlEvents:]
さまざまなコントロール イベントに対して をさらに呼び出すことができます。
参考:AppleのUIButtonクラスリファレンス