0

タイトル ビュー プロパティを使用してナビゲーション タイトル ビューに 2 つのボタンを追加する方法を教えてください。試してみましたが、次のコードを使用してボタンを1つだけ追加できました。

UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
customView.backgroundColor = [UIColor redColor];

UIButton *b1 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
UIButton *b2 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];

[b1 setTitle:@"Hai" forState:UIControlStateNormal];
[b2 setTitle:@"Hello" forState:UIControlStateNormal];

[customView insertSubview:b1 atIndex:0];
[customView insertSubview:b2 atIndex:1];   

self.navigationItem.titleView = customView;
4

2 に答える 2

0

これは、両方のボタンに同じフレームを追加したためです。したがって、ボタンは実際には重なっています。代わりに次のコードを使用する必要があります。

UIButton *b1=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
UIButton *b2=[[UIButton alloc]initWithFrame:CGRectMake(60, 0, 50, 50)];

次に、これらのボタンをカスタム ビューに追加するだけです。

[cusotmView addSubView:b1];
[cusotmView addSubView:b2];

エラーの理由:

を直接追加することはできませんUIButtons。最初にラップする必要がありますUIBarButtonItems

サンプルコード:

UIBarButtonItem *btn1 = [[UIBarButtonItem alloc] initWithCustomView:b1];
UIBarButtonItem *btn2 = [[UIBarButtonItem alloc] initWithCustomView:b2];
[cusotmView addSubView:btn1];
[cusotmView addSubView:btn2];
于 2013-09-28T07:21:54.993 に答える