2011-10-04 13 views
8

私はUIButtonのサブクラスを作成して白い2px No Radiiボーダーを作成しましたが、今はボタンの状態に応じてフォント、フォント色、および背景色を「グローバルに」設定しようとしています。UIButtonサブクラス - プロパティの設定?

フォントが設定されていません。色も背景色もしないでください。どうしたの?ここに私のコードです。私はあなたが助けることを望む:)

- (id)initWithFrame:(CGRect)frame { 
self = [super initWithFrame:frame]; 
if (self) { 

    [[self titleLabel] setFont:[UIFont fontWithName:@"ZegoeUI" size:18]]; 
    [self setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted]; 
    [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 
    if(self.state == UIControlStateHighlighted) { 
     [self setBackgroundColor:[UIColor whiteColor]]; 
    } 
    else { 
     [self setBackgroundColor:[UIColor blackColor]]; 
    } 
} 
return self; 
} 





// Only override drawRect: if you perform custom drawing. 
// An empty implementation adversely affects performance during animation. 
- (void)drawRect:(CGRect)rect { 

      [self.layer setMasksToBounds:YES]; 
[self.layer setBorderWidth:2.0]; 
[self.layer setCornerRadius:0.0]; 
[self.layer setBorderColor:[[UIColor colorWithWhite:1.0 alpha:1.0] CGColor]]; 
} 

私は何か間違っているとは思わない。私はこのクラスを持っている、とIBのボタンをリンクしている、とクラスタイプを設定し...

おかげで、

ベンベン

答えて

17

を使用すると、IB、initWithFrame:にカスタムサブクラスボタンを作成している場合ではありませんと呼ばれる。 initWithCoder:を無効にするか、好ましくは、initWithFrame:initWithCoder:の両方と呼ばれる個別のセットアップ方法を作成する必要があります。最初のケースでは

- (id)initWithCoder:(NSCoder*)coder { 
self = [super initWithCoder:coder]; 
if (self) { 

    [[self titleLabel] setFont:[UIFont fontWithName:@"ZegoeUI" size:18]]; 
    [self setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted]; 
    [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 
    if(self.state == UIControlStateHighlighted) { 
     [self setBackgroundColor:[UIColor whiteColor]]; 
    } 
    else { 
     [self setBackgroundColor:[UIColor blackColor]]; 
    } 
} 
return self; 
} 
+0

私は正確にそれについて正確にどのように行きますか?私は大学に行ったことは一度もありません。これまでに教えられているのはすべてです。 – topLayoutGuide

+0

あなたと私の両方:)。更新された回答を参照 – jrturton

0

UIButtonクラスクラスタです。実際にはそれが表すクラスはプライベートなので、サブクラス化するべきではありません。ここで

+1

これは技術的にはクラスクラスターではありませんが、良い点があります。サブクラス化すると複雑になることがあります(http://stackoverflow.com/questions/816024/how-to-override-drawrect-in-uibutton- UIControlをサブクラス化する方が良いかもしれません。 – jrturton

1

は、私は(IBなし)それを行う方法は次のとおりです。

+ (instancetype)customButtonWithCustomArgument:(id)customValue { 
    XYZCustomButtom *customButton = [super buttonWithType:UIButtonTypeSystem]; 
    customButton.customProperty = customValue; 
    [customButton customFunctionality]; 
    return customButton; 
} 

UIButtonTypeSystemは一例であり、他のタイプでも動作します。

関連する問題