尝试在iOS中响应委托方法调用时加粗UIButton的titleLabel

10

我正在开发一个应用程序,在其中调用了UITextFieldDelegate方法:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { }

我成功地调用了它,并且在方法内,我启用了一个特定的按钮,这也很好地起作用。然而,我面临的问题是,当按钮可用时,我无法使按钮上的标题加粗。我在接口构建器中设置了字体,并试图以编程方式使标题加粗。以下是相关代码,显示了我正在做的事情:

        if ([keys count] == [_tireName count]) {

            [_doneButton setEnabled:YES];//this line works
            [[_doneButton titleLabel] setFont:[UIFont boldSystemFontOfSize:28]];//this line does nothing


        } else if ([keys count] < [_tireName count]){

            [_doneButton setEnabled:NO];//this line works
            [[_doneButton titleLabel] setFont:[UIFont systemFontOfSize:28]];//this line does nothing

        }
忽略 "if" 从句本身。我想要当按钮启用时按钮上的文本为粗体,当它被禁用时,按钮上的文本应该是“正常”的。我做错了什么?

你用什么字体?例如:Helvetica? - Magyar Miklós
如果您使用的是iOS 6及以上版本,则可以使用“-(void)setAttributedTitle:(NSAttributedString *)title forState:(UIControlState)state”函数。 - danypata
我应该使用哪个UIControlState? - syedfa
@incmiko:抱歉,我正在使用在Interface Builder中设置的System 24.0。 - syedfa
你能否向我展示如何使用方法(void)setAttributedTitle:(NSAttributedString *)title forState:(UIControlState)state? - syedfa
显示剩余2条评论
4个回答

30

如果您正在使用标准字体并希望将其加粗,这种方法更简洁:

[_doneButton.titleLabel setFont:[UIFont boldSystemFontOfSize:[UIFont systemFontSize]]];

这样,您就不必担心字体族或大小。


10
_doneButton.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:24];

这将使你的文本加粗,因为你正在使用系统字体,即Helvetica。希望能帮到你。


5

Swift 3

doneButton.titleLabel?.font = UIFont.systemFont(ofSize: 28, weight: UIFontWeightBold)

以下是可用的权重:
UIFontWeightUltraLight
UIFontWeightThin
UIFontWeightLight
UIFontWeightRegular
UIFontWeightMedium
UIFontWeightSemibold
UIFontWeightBold
UIFontWeightHeavy
UIFontWeightBlack

请注意,苹果的文档中有以下说明:
// Beware that most fonts will _not_ have variants available in all these weights!

3
与BooTooMany的答案类似,但我发现实际上在UIButton中使用时它改变了大小。
我使用了:
[_doneButton.titleLabel setFont:[UIFont boldSystemFontOfSize:_doneButton.titleLabel.font.pointSize]];

那样做可以保持字体大小不变,只是将其加粗。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接