【问题标题】:Set color of NSButton programmatically swift以编程方式快速设置 NSButton 的颜色
【发布时间】:2015-04-02 16:53:03
【问题描述】:

我使用以下代码以编程方式生成一些 NSButton:

for i in 1...height {
        for j in 1...width {
            var but = NSButton(frame: NSRect(x: x, y: y + 78, width: 30, height: 30))
            but.tag = k
            but.title = ""
            but.action = Selector("buttonPressed:")
            but.target = self
            but.bezelStyle = NSBezelStyle(rawValue: 6)!
            but.layer?.backgroundColor = NSColor.blackColor().CGColor

            var ges = NSClickGestureRecognizer(target: self, action: Selector("addFlag:"))
            ges.buttonMask = 0x2
            ges.numberOfClicksRequired = 1
            but.addGestureRecognizer(ges)

            ar.append(but)
            self.view.addSubview(but)
            x += 30
            k++
        }
        y += 30
        x = 0
    }

我需要将所有按钮的背景颜色设置为灰色或黑色(随机)。我不知道如何获取或设置 NSButton 背景颜色。我对 swift 编程很陌生,我不太了解 obj-c,所以如果你能在 swift 上编写它,我将不胜感激!

【问题讨论】:

    标签: macos cocoa swift background-color nsbutton


    【解决方案1】:

    我正在使用此代码进行操作

    final class MyButton: NSButton {
        override func awakeFromNib() {
            let layer = CALayer()
            layer.backgroundColor = CGColorCreateGenericRGB(59.0/255, 52.0/255.0, 152.0/255.0, 1.0)
            self.wantsLayer = true
            self.layer = layer
        }
    }
    

    【讨论】:

      【解决方案2】:

      我通过 NSButton 参考指南阅读,似乎改变它的唯一方法是改变图像。但是我已经找到了一种使用颜色创建图像的方法。在类文件的顶部添加这个扩展

      extension NSImage {
      class func swatchWithColor(color: NSColor, size: NSSize) -> NSImage {
          let image = NSImage(size: size)
          image.lockFocus()
          color.drawSwatchInRect(NSMakeRect(0, 0, size.width, size.height))
          image.unlockFocus()
          return image
         }
      }
      

      这将允许我们稍后使用 UIColour 创建 NSImage。最后,当您要创建按钮时,请使用我们制作的扩展名设置图像。

       myButton.image = NSImage.swatchWithColor( NSColor.blackColor(), size: NSMakeSize(100, 100) )
      

      对于 size 参数,将其设置为按钮的大小。

      更新*如果你想随机选择颜色,你可以这样做..

       var randomIndex = arc4random_uniform(2) + 1 //Creates a random number between 1 and 2  
       var colour = NSColor() //Empty colour
      
          if randomIndex == 1 {
      
              //If the random number is one then the colour is black
              colour = NSColor.blackColor()
          }
      
          else {
      
              //Else if it's not one it's grey
              colour = NSColor.grayColor()
          }
      
          //set the button's image to the new colour
          myButton.image = NSImage.swatchWithColor(colour, size: //My button size)
      

      要获得大小,请转到您的故事板,单击您的按钮并转到标尺选项卡。它会显示您的按钮的大小。

      【讨论】:

      • 非常感谢,我知道如何随机选择颜色,但第一部分很棒!
      • 很高兴为您提供帮助:)
      【解决方案3】:

      坏消息是,恕我直言,没有给按钮着色的好方法;它们都有优点和缺点。 对于像我一样对 Yosemite 下的按钮着色感到好奇的每个人,我写的可能不是最终的按钮着色指南,但绝对是一个强有力的竞争者:

      http://www.extelligentcocoa.org/colouring-buttons/

      这涵盖了所有样式的按钮,并有几乎任何组合的屏幕截图,使用

      • 背景颜色
      • drawRect
      • 单元格背景颜色
      • 单色图层效果
      • whiteBalance 调整 layerEffect
      • 在 IB 中设置的图像
      • 继承 NSButton 并根据按钮状态添加图像

      如果有人能想到另一种给按钮上色的方法,我很想知道!

      【讨论】:

      • 我很抱歉 - 网站被黑了,我不得不重新安装内容;很抱歉错过了这个。
      • 链接仍然无效。
      • 时机不好 - 网站再次被黑客入侵,我正在转向更安全的提供商;完成后将立即更新。 (Wordpress 吸引了源源不断的黑客是什么?)
      • 链接仍然无效。
      • 链接有效! (我已经为 macOS 10.11 和 Storyboards 更新了这个)。
      【解决方案4】:

      好的,当我需要更改按钮的外观时,我会这样做:子类化它。

      //
      //  LSButtonColor.swift
      //
      //  Created by Lloyd Sargent on 8/26/16.
      //  Copyright © 2016 Canna Software. All rights reserved.
      //  License: Permission is hereby granted, free of charge, to any 
      //           person obtaining a copy of this software and associated
      //           documentation files (the “Software”), to deal in the 
      //           Software without restriction, including without
      //           limitation the rights to use, copy, modify, merge, 
      //           publish, distribute, sublicense, and/or sell copies of 
      //           the Software, and to permit persons to whom the Software 
      //           is furnished to do so, subject to the following
      //           conditions:
      //           
      //           The above copyright notice and this permission notice
      //           shall be included in all copies or substantial portions
      //           of the Software.
      //
      //           THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF
      //           ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
      //           TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
      //           PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
      //           SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
      //           CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
      //           OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
      //           IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
      //           DEALINGS IN THE SOFTWARE.
      //
      
      import Cocoa
      
      class LSButtonColor: NSButton {
      
      fileprivate struct AssociatedKeys {
          static var variableDictionary = "ls_variableDictionary"
      }
      
      fileprivate var variableDictionary: [String:AnyObject]! {
          get {
              var localVariableDictionary = objc_getAssociatedObject(self, &AssociatedKeys.variableDictionary) as! [String:AnyObject]!
              if localVariableDictionary == nil {
                  localVariableDictionary = [String:AnyObject]()
                  objc_setAssociatedObject(self, &AssociatedKeys.variableDictionary, localVariableDictionary, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
              }
              return localVariableDictionary
          }
          set(updatedDictionary) {
              objc_setAssociatedObject(self, &AssociatedKeys.variableDictionary, updatedDictionary, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
          }
      }
      
      var backgroundColor: NSColor! {
          get {
              return variableDictionary["backgroundColor"] as? NSColor
          }
          set(newBackgroundColor) {
              var localVariableDictionary = variableDictionary
              localVariableDictionary?["backgroundColor"] = newBackgroundColor
              variableDictionary = localVariableDictionary
          }
      }
      
      var altBackgroundColor: NSColor! {
          get {
              return variableDictionary["altBackgroundColor"] as? NSColor
          }
          set(newAltBackgroundColor) {
              var localVariableDictionary = variableDictionary
              localVariableDictionary?["altBackgroundColor"] = newAltBackgroundColor
              variableDictionary = localVariableDictionary
          }
      }
      
      var borderColor: NSColor! {
          get {
              return variableDictionary["borderColor"] as? NSColor
          }
          set(newBorderColor) {
              var localVariableDictionary = variableDictionary
              localVariableDictionary?["borderColor"] = newBorderColor
              variableDictionary = localVariableDictionary
      
              self.layer?.borderColor = newBorderColor.cgColor
          }
      }
      
      var cornerRadius: CGFloat {
          get {
              return variableDictionary["cornerRadius"] as! CGFloat
          }
          set(newCornerRadius) {
              var localVariableDictionary = variableDictionary
              localVariableDictionary?["cornerRadius"] = newCornerRadius as AnyObject?
              variableDictionary = localVariableDictionary
      
              self.layer?.cornerRadius = newCornerRadius
          }
      }
      
      var borderWidth: CGFloat {
          get {
              return variableDictionary["borderWidth"] as! CGFloat
          }
          set(newBorderWidth) {
              var localVariableDictionary = variableDictionary
              localVariableDictionary?["borderWidth"] = newBorderWidth as AnyObject?
              variableDictionary = localVariableDictionary
      
              self.layer?.borderWidth = newBorderWidth
          }
      }
      
      override func draw(_ dirtyRect: NSRect) {
          super.draw(dirtyRect)
      
          // Drawing code here.
          if self.isHighlighted {
              if self.layer != nil {
                  self.layer?.backgroundColor = self.altBackgroundColor.cgColor
              }
          }
          else {
              if self.layer != nil {
                  self.layer?.backgroundColor = self.backgroundColor.cgColor
              }
          }
        }
      }
      

      好的,您可能会感到困惑的第一件事是objc_getAssociatedObject - 最初我将其作为一个类别进行,这是一种向类别添加变量的简单方法(每个人都说你不能这样做,但是每个人都没有意识到,是的,你可以 - 这并不明显)。

      不幸的是,我遇到了一些问题,所以我只是把它变成了一个类 - 并没有费心取出关联的对象(为什么会搞砸成功?)

      无论如何,你应该可以拉出相关代码来改变任何按钮的背景。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-06
        • 2021-10-18
        • 2015-05-17
        • 2013-07-23
        • 2017-12-30
        • 2015-07-01
        • 2020-01-13
        相关资源
        最近更新 更多