How do you set the font size on a UIBarButtonItem?

前端 未结 5 1940
旧巷少年郎
旧巷少年郎 2021-02-03 19:42

I can\'t find a way to set the font size of the title in a custom UIBarButtonItem. The only way I can think of getting around this is to set it as an image which I would like to

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-03 19:55

    As a concrete example of what KennyTM suggests, you create the UIBarButtonItem with something like the following (in code):

    UILabel *txtLabel = [[UILabel alloc] initWithFrame:rect];
    txtLabel.backgroundColor = [UIColor clearColor];
    txtLabel.textColor = [UIColor lightGrayColor];
    txtLabel.text = @"This is a custom label";
    UIBarButtonItem *btnText = [[[UIBarButtonItem alloc] initWithCustomView:txtLabel] autorelease];
    

    Then, you can add it as centered text on a UIToolbar (for instance) with the following:

    UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:rect];
    toolBar.barStyle = UIBarStyleBlackTranslucent;
    UIBarButtonItem *flexSpace1 = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease];
    UIBarButtonItem *flexSpace2 = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease];
    
    [toolBar setItems:[NSArray arrayWithItems:flexSpace1, btnText, flexSpace2, nil]];
    

    (of course, to get proper formatting, the rect used for initializing txtLabel and toolBar should be the proper sizes.... but that's another exercise!)

提交回复
热议问题