以编程方式在UIViewController中的UINavigationBar中设置Left和Right标签

时间:2012-11-04 12:04:29

标签: objective-c uiviewcontroller uinavigationcontroller uinavigationbar xcode4.3

我正在尝试添加两个标签 - 一个在UIVavigationBar的左边和一个右边,在我的UIViewController实现中以编程方式。但是,当我运行程序时,它不会显示出来。我有一个嵌入在UINavigationController中的UIViewController。我使用以下代码:

- (void) setTheNavigationbarView{

    CGFloat originX = self.navigationItem.titleView.bounds.origin.x;
    CGFloat originY = self.navigationItem.titleView.bounds.origin.y;
    CGFloat sizeW = self.navigationItem.titleView.bounds.size.width;
    CGFloat sizeH = self.navigationItem.titleView.bounds.size.height;

    UIView * navigationbarView = [[UIView alloc] initWithFrame:CGRectMake(originX + 1, originY + 1, sizeW - 2, sizeH - 2)];
    navigationbarView.backgroundColor = [UIColor clearColor];


    UILabel *labelLeft = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, (sizeW - 2)/2, (sizeH - 2))] autorelease];
    labelLeft.backgroundColor = [UIColor clearColor];
    labelLeft.font = [UIFont boldSystemFontOfSize:16];
    labelLeft.adjustsFontSizeToFitWidth = NO;
    labelLeft.textAlignment = UITextAlignmentLeft;
    labelLeft.textColor = [UIColor blackColor];
    labelLeft.text = @"first line";
    labelLeft.highlightedTextColor = [UIColor blackColor];
    [navigationbarView addSubview:labelLeft];

    UILabel *labelRight = [[[UILabel alloc] initWithFrame:CGRectMake(((sizeW - 2)/2 + 1), 0, (sizeW - 2)/2, (sizeH - 2))] autorelease];
    labelRight.backgroundColor = [UIColor clearColor];
    labelRight.font = [UIFont boldSystemFontOfSize:16];
    labelRight.adjustsFontSizeToFitWidth = NO;
    labelRight.textAlignment = UITextAlignmentRight;
    labelRight.textColor = [UIColor blackColor];
    labelRight.text = @"second line";
    labelRight.highlightedTextColor = [UIColor blackColor];
    [navigationbarView addSubview:labelRight];

    // set the view as navigationba title view
    self.navigationItem.titleView = navigationbarView;
}

我将不胜感激任何帮助。感谢。

1 个答案:

答案 0 :(得分:0)

我测试你的代码及其工作对我来说,我只会检查你的框架是否不大于你的navigationController的每个尺寸。