1

iOS アプリのすべてのボタンに小さなグラデーションを適用しようとしています。基本的にサブタイトル、ボーダー、グラデーションレイヤーをボタンに追加するこの関数を追加した UIButton のカテゴリを作成しました。

関数はロードされたビューで呼び出されます:

- (void)viewDidLoad
{
  [super viewDidLoad];
  [_myButton buttonWithSubtitle:@"test subtitle"];

}

そしてカテゴリ機能

- (void)buttonWithSubtitle:(NSString*)subtitleText
{
  UILabel *subTitle = [[UILabel alloc] initWithFrame:CGRectMake(80, 20, 100, 30)];
  [subTitle setText:subtitleText];
  [subTitle setTextColor:[UIColor colorWithRed:(144.0 / 255.0) green:(144.0 / 255.0) blue:(144.0 / 255.0) alpha:1.0]];
  [subTitle setBackgroundColor:[UIColor clearColor]];
  [subTitle setFont:[UIFont fontWithName:@"American Typewriter" size:12]];
  [self.titleLabel setFrame:CGRectMake(30, 20, 100, 30)];

  [self setTitle:@"Main title" forState:UIControlStateNormal];
  [self addSubview:subTitle];

  CAGradientLayer *btnGradient = [CAGradientLayer layer];
  btnGradient.frame = self.bounds;
  btnGradient.colors = [NSArray arrayWithObjects:
                        (id)[[UIColor colorWithRed:255.0f / 255.0f green:255.0f / 255.0f blue:255.0f / 255.0f alpha:1.0f] CGColor],
                        (id)[[UIColor colorWithRed:234.0f / 255.0f green:234.0f / 255.0f blue:234.0f / 255.0f alpha:1.0f] CGColor],
                        nil];

  [self.layer setMasksToBounds:YES];
  [self.layer setCornerRadius:5.0f];
  [self.layer setBorderWidth:0.8f];
  [self.layer setBorderColor:[[UIColor colorWithRed:200.0f / 255.0f green:200.0f / 255.0f blue:200.0f / 255.0f alpha:1.0f] CGColor]];

  [self.layer insertSublayer:btnGradient atIndex:0];
}

私の問題は、上記の関数が呼び出されると、グラデーションがはっきりと見え、ボタンが目的のデザインになることです。ただし、以下の別のカテゴリ関数を使用して設定した、字幕のないボタン タイプもあります。

- (void)defaultButton
 {
  CAGradientLayer *btnGradient = [CAGradientLayer layer];
  btnGradient.frame = self.bounds;
  btnGradient.colors = [NSArray arrayWithObjects:
                        (id)[[UIColor colorWithRed:255.0f / 255.0f green:255.0f / 255.0f blue:255.0f / 255.0f alpha:1.0f] CGColor],
                        (id)[[UIColor colorWithRed:234.0f / 255.0f green:234.0f / 255.0f blue:234.0f / 255.0f alpha:1.0f] CGColor],
                        nil];

  [self.layer setMasksToBounds:YES];
  [self.layer setCornerRadius:5.0f];
  [self.layer setBorderWidth:0.8f];
  [self.layer setBorderColor:[[UIColor colorWithRed:200.0f / 255.0f green:200.0f / 255.0f blue:200.0f / 255.0f alpha:1.0f] CGColor]];

  [self.layer insertSublayer:btnGradient atIndex:0];
}

前のようにviewdidloadで呼び出されたこの関数を使用すると、グラデーションや背景がまったくないボタンになります(ボタンには明確な背景色があります..ボタンからビューコントローラーのビューの背景を見ることができます)。

- (void)viewDidLoad
{
  [super viewDidLoad];
  [_myButton defaultButton];

}

私のボタンはすべて、画像とデフォルトのタイトルを持つカスタムボタンとして設定されています。ご協力いただきありがとうございます

4

1 に答える 1

2

字幕付きのコードが機能する理由はわかりませんが、問題が見つかりました。問題は、自動レイアウトが有効になっていると、viewDidLoad メソッド中にボタンにまだフレームがないことです。

メソッドのようにボタンのレイヤーがある場合は、後でグラデーションを適用する必要があります

viewDidLayoutSubviews

参照:ストーリーボードの自動レイアウトが有効になっている iOS6 ではカスタム UIButton を実行できません

于 2013-04-15T21:07:02.903 に答える