ios - 如何在 iOS/xcode 中重用颜色和样式?

标签 ios swift user-interface design-patterns code-reuse

Android、WPF 以及我使用过的大多数平台,都可以在单个文件中重用和“集中”诸如颜色和​​样式之类的 UI 资源。

在android中可以这样做:

在 colors.xml 文件中:

<color name="secondary_text_color">#ffcc67</color>

在任何 View 中:

<TextView text="some text" textColor="@colors/secondary_text_color" />

iOS 中有类似的东西吗?

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

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

最佳答案

您可以使用任何单例类或 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)
    }
}

稍后您可以访问颜色

textField.textColor = UIColor.someColor2()

编辑: 您也可以对样式执行相同的操作,使用 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
    }
}

当你需要样式的时候,你会调用like

someLabel.attributedText = StyleHelper.getSecondaryTextWithString("SomeText")

关于ios - 如何在 iOS/xcode 中重用颜色和样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35174638/

相关文章:

ios - Swift:协议(protocol)方法作为目标 Action 中的 Action

iphone - View Controller 和 UIView 之间的简单委托(delegate)不起作用

ios - Swift:委托(delegate)/事件来自 C# 背景

swift - MVP - 在 iOS 中解散时从 View Controller 中销毁 Presenter 对象

java - 通过为 JButton 着色的俄罗斯方 block GUI。渲染问题

delphi - 如何在Delphi中最好地创建HMI显示面板(用户定制界面)

ios - Swift - 圆角类未应用于所有 UIView

ios - 如何检查 Firebase 权限是否被拒绝?

ios - 如何在 Avfoundation 中正确更改采样率

php - 用于 PHP 的表单生成器 GUI