How Can I Define a Custom Color That Is Available Both Programmatically And In IB?

时间:2017-08-05 11:34:27

标签: ios xcode

I want to be able to define a custom color in a single place and then have access to it both programmatically and in Interface Builder. For coding I could create a UIColor extension. For visual designing in IB I could create a custom color palette. What is the best technique that will simultaneously work with both?

4 个答案:

答案 0 :(得分:3)

Unfortunately you can't do this.

You can define a colour that you can access in code through an extension of UIColor. Or you can add a colour to the pallets in Interfact Builder.

But you can't have both.

Hmm...

What you could do is something similar to what PaintCode does.

Create an object in code that has a IBOutletCollection and then when the view loads it will iterate the outlets and set the background colour etc... to your fancy colour.

答案 1 :(得分:2)

Xcode 9允许您在资产目录中放置颜色。这是Apple对那些希望颜色同步的人的回答。

答案 2 :(得分:0)

如果你的颜色是变量,你也可以创建UIView的子类:

class ViewController: NSViewController, NSSearchFieldDelegate {

// Search Field
@IBOutlet weak var mySearchField: NSSearchField!

override func viewDidLoad() {
    super.viewDidLoad()

    // Don't forget to set delegate
    self.mySearchField.delegate = self

}

// Driver program
@IBAction func onPress(_ sender: Any) {
    // clear search field
    self.mySearchField.reset()
}

// View output
override func controlTextDidChange(_ obj: Notification) {
    print("--");
}
}

extension NSSearchField {

func reset() {
    self.stringValue = ""
    //let cell = self.cell as? NSSearchFieldCell
    //let cancelButton = cell?.cancelButtonCell
    //cancelButton?.performClick(self)
}
}

答案 3 :(得分:0)

现在有可能。

使用颜色名称创建颜色集,您可以在代码以及界面生成器中按颜色名称访问它们。

参考:https://medium.com/bobo-shone/how-to-use-named-color-in-xcode-9-d7149d270a16