如何更改分段控件的字体大小,并防止它在更改段后更改回默认大小

时间:2012-02-28 22:59:55

标签: objective-c ios uisegmentedcontrol font-size

我使用以下代码实现并随后更改UISegmented控件中每个段的字体大小

//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]];
        }
    }           
}

这最初有效(见下面的截图)

enter image description here

但是,点击“热门”标签(非活动标签)后,字体大小似乎恢复为原始默认字体大小

enter image description here

如何防止字体大小更改回默认大小?

2 个答案:

答案 0 :(得分:9)

可能不是最干净的方法,但是如果你在UISegmentedControl控件的'value Changed'事件上运行for循环,它就可以工作。

<强>更新 这是正确的方法,可在iOS 5及更高版本中使用:

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

答案 1 :(得分:1)

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

看看它的答案

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