在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];
我希望选定的文本是粗体,否则它应该是正常的。
答
我已经尝试过了类似下面
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]
也改变了突出选定。
答
变化
[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(),或者如果您是子类,则将其作为单独的函数添加。
我设法只改变文字颜色,设置字体没有做任何改变 –
你试过UIControlStateSelected了吗? – Tim
不,我没有尝试,现在我又增加了一行:[self.tab setTitleTextAttributes:boldAttributes forState:UIControlStateSelected]; – Shahnawaz