web-dev-qa-db-ja.com

iPhone:buttonType UIButtonTypeCustomを使用してUIButtonのBackgroundColorを設定する方法

クリックしたときにボタンの色を変更したい。私は使用しました:

[button setBackgroundColor:[UIColor redColor]];

しかし、これはボタン全体ではなくボタンの四隅でのみ赤色を示し、_forState:UIControlStateNormalその後、アプリケーションがハングします。クリックしたときにボタンに色を表示する方法はありますか?

[click1 setBackgroundColor:[UIColor redColor] forState:UIControlStateHighlighted];

任意の助けをいただければ幸いです。

33
Pankaj Kainthla

プログラムでイメージを作成し、動的に色を使用することができます。

このメソッドでUIButtonのカテゴリを作成し、@import QuartzCoreを介してQuartzCore libをインポートしてください。

- (void)setColor:(UIColor *)color forState:(UIControlState)state
{
    UIView *colorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
    colorView.backgroundColor = color;

    UIGraphicsBeginImageContext(colorView.bounds.size);
    [colorView.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *colorImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [self setBackgroundImage:colorImage forState:state];
}

これにより、指定した色のボタンのサイズで画像が作成され、希望する状態に割り当てられます。 backgroundImageを使用するため、setTitle:forState:メソッドを使用してボタンのタイトルを設定できます。

38
Hendrik

これは私がしていることです...それはUIButtonのカスタムサブクラスで、通常の色と強調表示された色を設定するだけで、すべてがうまく動作します;)

ヘッダーファイル:

//
//  FTCustomButton.h
//  FTLibrary
//
//  Created by Ondrej Rafaj on 14/01/2013.
//  Copyright (c) 2013 Fuerte International. All rights reserved.
//

#import <UIKit/UIKit.h>


@interface FTCustomButton : UIButton

@property (nonatomic, strong, readonly) UIColor *normalColor;
@property (nonatomic, strong, readonly) UIColor *highlightedColor;

- (void)setNormalColor:(UIColor *)normalColor;
- (void)setHighlightedColor:(UIColor *)highlightedColor;


@end

これは実装ファイルです。

//
//  FTCustomButton.m
//  FTLibrary
//
//  Created by Ondrej Rafaj on 14/01/2013.
//  Copyright (c) 2013 Fuerte International. All rights reserved.
//

#import "FTCustomButton.h"

//*****************************************************************************
// private interface declaration
//*****************************************************************************
@interface MCSelectionButton ()
    @property(nonatomic, strong, readwrite) UIColor *normalColor;
    @property(nonatomic, strong, readwrite) UIColor *highlightedColor;
@end

//*****************************************************************************
// public interface implementation
//*****************************************************************************

@implementation FTCustomButton


#pragma mark Settings

- (void)setNormalColor:(UIColor *)normalColor {
    [self setBackgroundColor:normalColor];
    _normalColor = normalColor;
}

- (void)setHighlightedColor:(UIColor *)highlightedColor {
    _highlightedColor = highlightedColor;
}

#pragma mark Actions

- (void)didTapButtonForHighlight:(UIButton *)sender {
    [self setBackgroundColor:_highlightedColor];
}

- (void)didUnTapButtonForHighlight:(UIButton *)sender {
    [self setBackgroundColor:_normalColor];
}

#pragma mark Initialization

- (void)setupButton {
    [self addTarget:self action:@selector(didTapButtonForHighlight:) forControlEvents:UIControlEventTouchDown];
    [self addTarget:self action:@selector(didUnTapButtonForHighlight:) forControlEvents:UIControlEventTouchUpInside];
    [self addTarget:self action:@selector(didUnTapButtonForHighlight:) forControlEvents:UIControlEventTouchUpOutside];
}

- (id)init {
    self = [super init];
    if (self) {
        [self setupButton];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setupButton];
    }
    return self;
}

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


@end
14
Ondrej

他の誰かが既に述べたように、ボタンのタイプがカスタムであることを確認してください。その後、次の操作を行うと、丸みを帯びた角が戻ります。

 [self.myButton.layer setCornerRadius:8.0f];
 [self.myButton.layer setMasksToBounds:YES];
 [self.myButton.layer setBorderWidth:1.0f];
 [self.myButton.layer setBorderColor:[[UIColor whiteColor] CGColor]];
 self.myButton.backgroundColor = [UIColor redColor];

個人的には、私は無地のグラデーションボタンの大ファンです...また、背景色には異なる状態がありませんが、背景画像にはあります:

 [self.myButton setBackgroundImage:[UIImage imageNamed:@"gradient.png"] forState:UIControlStateNormal];

画像を使用すると、ボタンは選択範囲とともに暗くなります(または、状態ごとに異なる背景画像を指定して、異なる操作を行うことができます)。これは背景色では発生しません。背景は常に同じままで、ボタンラベルのみが状態ごとに変化します。

13
DiggyJohn

Dimaの回答を完了し、Swiftに拡張機能を実装しました。

extension UIButton {
    private func imageWithColor(color: UIColor) -> UIImage {
        let rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()

        CGContextSetFillColorWithColor(context, color.CGColor)
        CGContextFillRect(context, rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }

    func setBackgroundColor(color: UIColor, forUIControlState state: UIControlState) {
        self.setBackgroundImage(imageWithColor(color), forState: state)
    }
}
7
Giordano Scalzo

リストされているどのソリューションよりも効率的なソリューションは、Core Graphicsで直接画像を描画することです。 UIViewを作成してrenderInContext:を呼び出す必要はありません。 かなり遅くなる可能性があります

+ (UIImage *) imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

UIImageカテゴリでこれを使用して、UIButtonで使用する画像を作成できます。

4
Dima

ボタンに赤い色の画像を用意し、ユーザーがクリックしたときにそれを設定できます

[yourButtonName setBackgroundImage:[UIImage imageNamed:@"yourRedButton.png"] forState:UIControlStateHighlighted];
2
Gyani

単色のボタンを取得するには、ボタンをカスタムボタンに設定できます。利用可能なボタンapiの既知のリストを次に示します(アウトレットとして設定した後、viewDidLoadで設定できます)。クォーツをインポートし、境界線の半径を変更して、ボタンのように見せます。

//highlightcolor - this changes the status for UIControlStateHighlighted
OUTLETNAME.tintColor =  [UIColor orangeColor];

//borderradius *quartz
[[OUTLETNAME layer] setCornerRadius:20.0f];

//border *quartz
[[OUTLETNAME layer] setBorderWidth:5.0f];

//bordercolor
[OUTLETNAME.layer setBorderColor:[[UIColor greenColor] CGColor]];

//backgroundcolor 
OUTLETNAME.backgroundColor = [UIColor blackColor];

//image 
[OUTLETNAME setImage:[UIImage imageNamed:PICNAME] forState:UIControlStateNormal];

//text 
[OUTLETNAME setTitle:@"TEXT" forState:UIControlStateNormal];

//fontsize
OUTLETNAME.titleLabel.font = [UIFont systemFontOfSize:36.0];

//fontcolor
OUTLETNAME.titleLabel.textColor = [UIColor blackColor];

//fontcolor
[OUTLETNAME setTitleColor:[UIColor orangeColor] forState: UIControlStateNormal];

グラデーション色のカスタムボタンが必要な場合は、カスタムボタンクラスを作成する必要があります。

このブログには、ダウンロード用の光沢のあるボタンクラスプロジェクトがあります。 http://didikot.com/?p=217

それを使用するには屈折してARCに変換する必要があると思います。

このブログは同じことをしていますが、光沢はありません。 http://www.cimgf.com/2010/01/28/fun-with-uibuttons-and-core-animation-layers/

2
MGM

Hendrikの回答の更新です。

自動レイアウトでうまく機能するには、UIViewフレームサイズをボタン固有のコンテンツサイズに設定する必要があります。そうしないと、レイアウトが台無しになります。

- (void)setColor:(UIColor *)color forState:(UIControlState)state
{
    UIView *colorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.intrinsicContentSize.width, self.intrinsicContentSize.height)];
    colorView.backgroundColor = color;

    UIGraphicsBeginImageContext(colorView.bounds.size);
    [colorView.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *colorImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [self setBackgroundImage:colorImage forState:state];
}
1
BrunoVillanova

@pankaj Gyaniは正しいと言う

UIButton *button = [[UIButton buttonWithType:UIButtonTypeCustom] initWithFrame:CGRectMake(0, 0, 24, 24)];
[button addTarget:self action:@selector(prevButtonClick:) forControlEvents:UIControlEventTouchUpInside];
[button setBackgroundImage:[UIImage imageNamed:@"IntroArrowLeft.png"] forState:UIControlStateNormal];
[self addSubview:button];
1
arunkumar.p

UIButtonのタイプをカスタムに設定し、その画像または背景画像のプロパティを通常状態および強調表示状態に設定する必要があります。

アプリで簡単に使用できるプロフェッショナルで見栄えの良いボタンの場合 this カスタムボタンコンポーネントも役立ちます。

1
Ahmet Ardal

あなたはすべて正しいです。ボタンの種類をUIButtonTypeCustomに設定するだけです。

button =    [UIButton buttonWithType:UIButtonTypeCustom];
button.frame    =   CGRectMake(200, 8, 100, 30);
[button setTitle:@"Set up" forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor greenColor]];
button.clipsToBounds    =   YES;
button.layer.cornerRadius   =   10;
button.alpha        =   0.5;
1
Shob-Z

ボタンの種類をカスタムにします。

例えば

button = [UIButton buttonWithType:UIButtonTypeCustom];

ではごきげんよう。

0
Warrior

@Dimaに感謝

Swift 3.0をUIButton拡張として使用するための更新コードです

extension UIButton {
  // thanks to @Dima http://stackoverflow.com/a/24665476/2581637 update code for Swift 3
  func setBackgroundColor(color: UIColor, forUIControlState state: UIControlState) {
    func imageWithColor(color: UIColor) -> UIImage? {
      let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
      UIGraphicsBeginImageContext(rect.size)
      if let context = UIGraphicsGetCurrentContext() {
        context.setFillColor(color.cgColor)
        context.fill(rect)
      }

      let image = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()

      return image
    }

    self.setBackgroundImage(imageWithColor(color: color), for: state)
  }
}
0
nuynait