如何在导航栏上设置UILabels

时间:2015-11-10 07:00:59

标签: ios objective-c

您好我已经尝试在导航栏上设置UILabels。在potrait模式下它适合正确但是当我们旋转横向模式时它不合适。请帮助我任何一个。

我的代码如下:

CGRect frame = self.navigationController.navigationBar.frame;

 UILabel *lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, frame.size.width/2, 44)];
        lbl1.backgroundColor = [UIColor redColor];
        lbl1.textAlignment = NSTextAlignmentCenter;
        lbl1.text = @"Dashboard";     

 UILabel *lbl2 = [[UILabel alloc] initWithFrame:CGRectMake(frame.size.width/2, 0, frame.size.width/2, 44)];
    lbl2.backgroundColor = [UIColor redColor];
    lbl2.textAlignment = NSTextAlignmentCenter;
    lbl2.text = @"Profile";

 UIView *customView  = [[UIView alloc]initWithFrame:frame];   
    [customView addSubview:lbl1];
    [customView addSubview:lbl2];
    self.navigationItem.titleView = customView;

enter image description here

3 个答案:

答案 0 :(得分:0)

试试这个。

CGRect frame = self.navigationController.navigationBar.frame;
UIView *customView  = [[UIView alloc]initWithFrame:frame];
customView.backgroundColor = [UIColor redColor];
[customView addSubview:lbl1];
[customView addSubview:lbl2];
self.navigationItem.titleView = customView;

答案 1 :(得分:0)

在横向和纵向模式下工作,请尝试使用此代码

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft || [[UIDevice currentDevice] orientation ]== UIDeviceOrientationLandscapeRight)
    {
        NSLog(@"Lanscapse");
        [self ViewFrameSet];
    }
    if([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait || [[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown )
    {
        NSLog(@"UIDeviceOrientationPortrait");
        [self ViewFrameSet];
    }
}
-(void)ViewFrameSet
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)];
    view.backgroundColor=[UIColor redColor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width/2, 44)];
    label.text = @"Dashboard";
    label.backgroundColor=[UIColor clearColor];
    label.textAlignment = NSTextAlignmentCenter;
    [view addSubview:label];

    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/2, 0, [UIScreen mainScreen].bounds.size.width/2, 44)];
    label1.text = @"Profile";
    label1.backgroundColor=[UIColor clearColor];
    label1.textAlignment = NSTextAlignmentCenter;
    [view addSubview:label1];

    self.navigationItem.titleView = view;
}

我希望这会对你有所帮助。 如果你喜欢我的答案那么接受并提出我的答案

答案 2 :(得分:0)

首先你应该得到导航栏的大小。当你成像时,高度就是问题,不适合导航栏。

当您更改为landScapeMode时,您应该将标签的框架重置为landScapeMode的navagationBar的高度。

希望能帮到你。