34

ナビゲーション バーの中央にカスタム ビューを追加しようとしています。次のコードを使用してテストしています。

UIView * testView = [[UIView alloc] init];
[testView setBackgroundColor:[UIColor blackColor]];
testView.frame = CGRectMake(0, 0, 100, 35);
[self.navigationController.navigationItem.titleView addSubview:testView];

ビューコントローラーのviewDidLoadメソッドでこれを設定していますが、プログラムを実行してもナビゲーションバーで何も変わらないようです。

これで私を助けてもらえますか?

4

8 に答える 8

69

これは機能します。初期化時にフレームを与える

UIView *iv = [[UIView alloc] initWithFrame:CGRectMake(0,0,32,32)];
[iv setBackgroundColor:[UIColor whiteColor]];
self.navigationItem.titleView = iv;
于 2011-12-08T15:19:34.760 に答える
27

交換

[self.navigationController.navigationItem.titleView addSubview:testView];

self.navigationItem.titleView = testView;

編集:

注: デフォルト値が であるため、サブビューを titleView に追加することはできませんnil。新しいビューを titleView として設定する必要があります。

于 2011-12-08T15:14:18.867 に答える
1
#import <UIKit/UIKit.h> 
@interface MasterViewController : UITableViewController
@end


#import "MasterViewController.h"
@interface MasterViewController ()
@end

@implementation MasterViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.titleView = [self titleView];
}

- (UIView *)titleView {
    CGFloat navBarHeight = self.navigationController.navigationBar.frame.size.height;
    CGFloat width = 0.95 * self.view.frame.size.width;
    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, navBarHeight)];

    UIImage *logo = [UIImage imageNamed:@"logo.png"];
    UIButton *logoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    CGFloat logoY = floorf((navBarHeight - logo.size.height) / 2.0f);
    [logoButton setFrame:CGRectMake(0, logoY, logo.size.width, logo.size.height)];
    [logoButton setImage:logo forState:UIControlStateNormal];

    UIImage *bubble = [UIImage imageNamed:@"notification-bubble-empty.png"];
    UIImageView *bubbleView = [[UIImageView alloc] initWithImage:bubble];

    const CGFloat Padding = 5.0f;
    CGFloat bubbleX = 
        logoButton.frame.size.width + 
        logoButton.frame.origin.x + 
        Padding;
    CGFloat bubbleY = floorf((navBarHeight - bubble.size.height) / 2.0f);
    CGRect bubbleRect = bubbleView.frame;
    bubbleRect.origin.x = bubbleX;
    bubbleRect.origin.y = bubbleY;
    bubbleView.frame = bubbleRect;

    [containerView addSubview:logoButton];
    [containerView addSubview:bubbleView];

    return containerView;
}

@end
于 2016-02-21T21:33:50.943 に答える
1
CustomLabel *titleLabel = [CustomLabel initWithLabelFrame:labelFrame textFont:[UIFont fontWithName:@"Helvetica" size:[UIFont systemFontSize]] textColor:[UIColor blackColor] labelText:@"Add as" textAlignment:NSTextAlignmentCenter labelOnView:reference.view labelTag:62];

[self.navigationItem setTitleView:titleLabel]; // titleLabel set in navigationItem
于 2015-09-13T06:22:47.360 に答える
0

iPhone 6 以降の (より大きな) デバイスをサポートするには、ストーリーボードを使用してこれを行う必要があります。

カスタム ナビゲーション アイテムのタイトル/サブタイトルなどのコンテナー ビューを作成し、それを (ビュー階層ではなく) ビジュアル エディターにドラッグします。

于 2015-06-17T21:37:17.897 に答える