简体   繁体   中英

How to change font size of segmented control and prevent it from changing back to default size after changing segment

I am using the following code to implement and subsequently change the font size of each segment in the UISegmented Control

//Set up segment control
UISegmentedControl *tempSegmentControl = [[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:@"Friends",@"Popular", nil]];
tempSegmentControl.frame = CGRectMake(-8, -1, 336, 30);

self.segmentControl = tempSegmentControl;
[self.segmentControl setWidth:168 forSegmentAtIndex:0];
[self.segmentControl setWidth:168 forSegmentAtIndex:1];
self.segmentControl.selectedSegmentIndex = 0;
[self.segmentControl addTarget:self action:@selector(toggleControls:) forControlEvents:UIControlEventValueChanged];
[self.segmentControl setSegmentedControlStyle:UISegmentedControlStylePlain];

//TO CHANGE FONT SIZE OF EACH SEGMENT
for (id segment in [self.segmentControl subviews]) 
{
    for (id label in [segment subviews]) 
    {
        if ([label isKindOfClass:[UILabel class]])
        {
            [label setTextAlignment:UITextAlignmentCenter];
            [label setFont:[UIFont boldSystemFontOfSize:14]];
        }
    }           
}

This works initially (see screenshot below)

在此输入图像描述

However, after I click on the "popular" tab (inactive tab), the font size seem to return to their original default font size

在此输入图像描述

What can I do to prevent the font size from changing back to the default size?

Probably not the cleanest way, but it works if you run the for-loop on the 'value Changed' event of the UISegmentedControl control.

Update: This is the proper way, available in iOS 5 and later:

NSDictionary *textAttributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:14], UITextAttributeFont, nil];
[self.segmentControl setTitleTextAttributes:textAttributes forState:UIControlStateNormal];

http://chris-software.com/index.php/tag/uisegmentedcontrol/

check out this its ans

codeButton.segmentedControlStyle = UISegmentedControlStyleBar;
codeButton.momentary = YES;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM