【问题标题】:Changing the color and font size of button titles in swift(for osx NOT ios)快速更改按钮标题的颜色和字体大小(对于 osx NOT ios)
【发布时间】:2016-05-12 16:14:45
【问题描述】:

我想更改其中一个按钮标题的颜色。首先我尝试了一些简单的猜测:

Button.title.textColor = NSColor(/*something*/)
Button.Color = NSColor( /*something*/ )
Button.textColor = NSColor( /*something*/ )

但他们没有工作。然后我在网上找到了如下代码:

Button.attributedTitle = NSAttributedString(string: /*something*/ , attributes: /*something*/ [NSForegroundColorAttributeName : NSColor( /*something*/ ), NSParagraphStyleAttributeName : NSMutableParagraphStyle() ])

但是它又长又复杂,如果不分配额外的特性就不能改变颜色(除了让它们保持在界面构建器中设置的默认值);另外,最重要的是,当我使用它时,它会将字体大小更改为小字体大小(忽略我在界面生成器中设置的字体大小)并且我不知道如何再次将其更改回来。 有没有更好的代码可以使用?如果不是,我如何在上面的代码中为字体大小赋值?

【问题讨论】:

  • 我刚刚做了。请参阅此帖子:stackoverflow.com/questions/31088172/… 以及此帖子:stackoverflow.com/questions/36831596/…
  • @Katherine Jenkins 这些帖子适用于 iOS 而不是 osx。我尝试了代码,但它们不起作用
  • 道歉。完全错过了。我的同事让我将您推荐给:stackoverflow.com/questions/28608727/… ...希望该链接更有帮助;)
  • 我已经知道了(正如我在问题中所写的那样)。我的问题是,当我使用它时,它会将字体大小更改为较小的字体大小,我不知道如何将其改回来
  • 为什么这个问题被否决了?这是一个非常清楚的问题:如何为按钮标题设置自定义颜色和字体大小?

标签: swift macos cocoa swift2


【解决方案1】:

如果你想改变按钮标题的颜色。用这个。

// redColor() 仅用作示例。

Button.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)

【讨论】:

  • 那是给 Ios 的。我正在为 osx 编程
【解决方案2】:

NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSColor (/**something*/) forKey:NSForegroundColorAttributeName];

NSAttributedString *attr = [[NSAttributedString alloc] initWithString:@"Text" attributes:dict];

[按钮 setAttributedTitle:attr];

【讨论】:

  • 当我使用它时,它会改变字体大小,我不知道如何将它改回来。这是我在问题中提到的问题
  • 您也可以将字体大小添加到属性字典中: [NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0], NSForegroundColorAttributeName, [NSFont fontWithName:@"HelveticaNeue" size:5.0f],NSFontAttributeName, nil];
  • 您可以使用以下代码获取您在界面生成器中设置的字体大小:float size = Button.font.pointSize;
【解决方案3】:

创建一个包含颜色和字体大小的属性字符串(更多信息:How do I make an attributed string using Swift? ) 然后使用

button.attributedTitle

设置标题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    相关资源
    最近更新 更多