如何重用iOS/xcode中的颜色和样式?

dan*_*ela 8 user-interface code-reuse design-patterns ios swift

Android,WPF以及我一直在使用的大多数平台都可以在单个文件中重用和"集中"ui资源,如颜色和样式.

在android中它可以这样做:

在colors.xml文件中:

<color name="secondary_text_color">#ffcc67</color>
Run Code Online (Sandbox Code Playgroud)

在任何视图中:

<TextView text="some text" textColor="@colors/secondary_text_color" />
Run Code Online (Sandbox Code Playgroud)

iOS中有类似的东西吗?

我不是想在iOS中复制android,但我正在努力理解应该遵循的ui重用模式(如果有的话).

我遇到的唯一的事情是在代码中定义主题,并在代码背后重用它,这是正确的方法吗?

Rav*_*avi 13

您可以使用任何单例类或UIColor扩展来完成此操作.以下是示例UIColor扩展.

import Foundation
import UIKit

extension UIColor
{
    class func someColor1() -> UIColor
    {
        return UIColor(red: 123.0/255.0, green: 162.0/255.0, blue: 157.0/255.0, alpha:1.0)
    }

    class func someColor2() -> UIColor
    {
        return UIColor(red: 154.0/255.0, green: 143.0/255.0, blue: 169.0/255.0, alpha:1.0)
    }
}
Run Code Online (Sandbox Code Playgroud)

稍后您可以访问颜色

textField.textColor = UIColor.someColor2()
Run Code Online (Sandbox Code Playgroud)

编辑:您也可以使用相同的样式 NSAttributedString

class StyleHelper : NSObject{

    class func getSecondaryTextWithString(textString:String) -> NSAttributedString
    {
        let secondaryTextStyleAttributes: [String : AnyObject] = [
            NSForegroundColorAttributeName: UIColor.greenColor(), NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleDouble.rawValue,NSFontAttributeName: UIFont.systemFontOfSize(14.0)]
        let secondaryTextStyleString = NSAttributedString(string: textString, attributes:secondaryTextStyleAttributes)
        return secondaryTextStyleString
    }
}
Run Code Online (Sandbox Code Playgroud)

当你需要这种风格时,你会打电话给

someLabel.attributedText = StyleHelper.getSecondaryTextWithString("SomeText")
Run Code Online (Sandbox Code Playgroud)