2012-01-25 10 views
0

UIButtonは、多くの状態依存の設定(image、titleColorなど)を提供します。 ボタンの状態の変化に反応するボタンにサブビューを手動で追加しました。 どうすればいいですか?状態の変更についてUIControlEventをマップする必要がありますか?UIButtonの状態変化を追跡するソリューション

答えて

6

あなたは、ボタンの選択や強調表示プロパティのKVOのオブザーバーを追加することによってそれを行うことができ、それはUIButtonのサブクラスを作成し、setSelectedsetHighlightedメソッドをオーバーロードよりも多く複雑です。

//MyCustomButton.h 

@interface MyCustomButton : UIButton 

@end 


//MyCustomButton.m 

@implementation MyCustomButton 

- (void)setUp 
{ 
    //add my subviews here 
} 

- (id)initWithFrame:(CGRect)frame 
{ 
    //this is called when you create your button in code 
    if ((self = [super initWithFrame:frame])) 
    { 
     [self setUp]; 
    } 
    return self; 
} 

- (id)initWithCoder:(NSCoder *)aDecoder 
{ 
    //this is called when you create your button in interface builder 
    if ((self = [super initWithCoder:aDecoder])) 
    { 
     [self setUp]; 
    } 
    return self; 
} 

- (void)setSelected:(BOOL)selected 
{ 
    super.selected = selected; 
    //update my subviews here 
} 

- (void)setHighlighted:(BOOL)highlighted 
{ 
    super.highlighted = highlighted; 
    //update my subviews here 
} 

@end 

次に、あなたのビューに定期的にUIButtonをドラッグすることで、インターフェイスビルダーでそれらをコードでカスタムボタンを作成するか、またはすることができ、その後、インスペクタでMyCustomButtonにそのクラスを設定:あなたはこのようにそれを行うだろう。

関連する問題