在UISegmentedControl的选定选项卡上可以有不同的样式字体吗?

问题描述:

我已经编写了这个代码来为UISegmentedControl设置正常状态和突出显示的状态的字体属性,但它不工作。请帮我指出原因。在UISegmentedControl的选定选项卡上可以有不同的样式字体吗?

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys: [UIFont fontWithName:@"Helvetica" size:12.0f], UITextAttributeFont, 

          [UIColor blackColor], UITextAttributeTextColor, 

          nil]; 

NSDictionary *boldAttributes = [NSDictionary dictionaryWithObjectsAndKeys: [UIFont fontWithName:@"Helvetica-Bold" size:12.0f], UITextAttributeFont, 

          [UIColor blackColor], UITextAttributeTextColor, 

          nil]; 



[self.tab setTitleTextAttributes:attributes forState:UIControlStateNormal]; 

[self.tab setTitleTextAttributes:boldAttributes forState:UIControlStateHighlighted]; 

我希望选定的文本是粗体,否则它应该是正常的。

+0

我设法只改变文字颜色,设置字体没有做任何改变 –

+0

你试过UIControlStateSelected了吗? – Tim

+0

不,我没有尝试,现在我又增加了一行:[self.tab setTitleTextAttributes:boldAttributes forState:UIControlStateSelected]; – Shahnawaz

我已经尝试过了类似下面

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys: 
         [UIFont boldSystemFontOfSize:17], UITextAttributeFont, 
         [UIColor blackColor], UITextAttributeTextColor, 
         nil]; 
[_segmentedControl setTitleTextAttributes:attributes forState:UIControlStateNormal]; 
NSDictionary *highlightedAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:UITextAttributeTextColor]; 
[_segmentedControl setTitleTextAttributes:highlightedAttributes forState:UIControlStateHighlighted]; 

,并设置字体

[UIFont fontWithName:@"FontName" size:desiredsize.f] 

也改变了突出选定。

+0

我之前将不同的标签颜色更改为浅蓝色和绿色,因为它是必需的,所以我不能将其更改为白色,因为它当时不能看到。一种方法来看看是否加粗,出于某种原因,我的代码无法工作。 – Shahnawaz

+0

此外,我只是试图改变高亮选择和相同的结果 – Shahnawaz

+0

你可以添加自己的色调,而不是我在我的代码中的颜色。而对于粗体的使用,只需在字体名称末尾加上一个。它通常适用于我,但请记住,for必须是uifont家族的一部分。 –

变化

[self.tab setTitleTextAttributes:boldAttributes forState:UIControlStateHighlighted]; 

[self.tab setTitleTextAttributes:boldAttributes forState:UIControlStateSelected]; 

这个答案是过时,但对于那些谁正在寻找迅速的解决方案,你可能会想尝试这种方法:

func stylizeFonts(){ 
    let normalFont = UIFont(name: "Helvetica", size: 16.0) 
    let boldFont = UIFont(name: "Helvetica-Bold", size: 16.0) 

    let normalTextAttributes: [NSObject : AnyObject] = [ 
     NSForegroundColorAttributeName: UIColor.blackColor(), 
     NSFontAttributeName: normalFont! 
    ] 

    let boldTextAttributes: [NSObject : AnyObject] = [ 
     NSForegroundColorAttributeName : UIColor.whiteColor(), 
     NSFontAttributeName : boldFont!, 
    ] 

    self.setTitleTextAttributes(normalTextAttributes, forState: .Normal) 
    self.setTitleTextAttributes(normalTextAttributes, forState: .Highlighted) 
    self.setTitleTextAttributes(boldTextAttributes, forState: .Selected) 
} 

确保在您的viewDidLoad中添加stylizeFonts(),或者如果您是子类,则将其作为单独的函数添加。