Can I center a UIToolbar item?

后端 未结 4 1288
遥遥无期
遥遥无期 2021-02-13 21:57

I am putting a label on a UIToolbar (per this tip: Adding a UILabel to a UIToolbar).

But the toolbar has a button on the left side, and so flexible spaces throw the labe

4条回答
  •  粉色の甜心
    2021-02-13 22:28

    To center a text/title on a toolbar you can use a simple UILabel like see below:

    UILabel *labelTitle = [[UILabel alloc] init];
    labelTitle.font =[UIFont fontWithName:@"Helvetica-Bold" size:18];
    labelTitle.backgroundColor = [UIColor clearColor];
    labelTitle.textAlignment = UITextAlignmentCenter;
    labelTitle.userInteractionEnabled = NO;
    labelTitle.text = @"Your Title";
    [labelTitle sizeToFit];
    CGRect labelTitleFrame = labelTitle.frame;
    labelTitleFrame.size.width = self.toolbar.bounds.size.width;
    labelTitleFrame.origin.y = (self.toolbar.bounds.size.height - labelTitleFrame.size.height) / 2;
    labelTitle.frame = labelTitleFrame;
    labelTitle.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    // Just add UILabel like UIToolBar's subview 
    [self.toolbar addSubview:labelTitle];
    [labelTitle release];
    labelTitle = nil;
    

提交回复
热议问题