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

Posted

技术标签:

【中文标题】如何在 iOS/xcode 中重用颜色和样式?【英文标题】:How to reuse colors and styles in iOS/xcode? 【发布时间】:2016-05-12 12:11:02 【问题描述】:

android、WPF 以及我使用过的几乎所有平台都可以在单个文件中重用和“集中”用户界面资源,例如颜色和样式。

在 android 中可以这样做:

在colors.xml文件中:

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

在任何视图中:

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

ios 中有类似的东西吗?

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

我遇到的唯一一件事就是在代码中定义 Theme,并在后面的代码中重用它,这样对吗?

【问题讨论】:

使用 PCH 文件定义具有 RGB 值的 uicolor 并继续使用该常量。 Swift 还是 Objective C? 萨赫布,你能举个例子吗? 【参考方案1】:

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

【讨论】:

我不确定这是否是对问题的(完整)答案,但我确实觉得它很有用,所以我现在会支持它。谢谢【参考方案2】:

添加到类的 raki 答案扩展,如 UIColor 或 UIFont 是我见过的最多的,即使你需要做更多的输入,它在 iOS 中也是等价的。

extension UIFont 
class func myFont() -> UIFont 
    return UIFont(name: "HelveticaNeue", size: 22)!


class func otherFont() -> UIFont 
    return UIFont(name: "Arial", size: 22)!

另一个可能与 android 相关的东西相当于 iOS 编程中的字符串文件,因为您似乎对重用这些样式感兴趣。对于字符串:

然后填写您将在应用中使用的字符串

"ACTION_CELL_MENU" =                "Menu";

然后在其他地方的代码中

label.text = NSLocalizedString("ACTION_CELL_MENU", comment: "")

【讨论】:

【参考方案3】:

相当老的问题,但您实际上可以向 Assets.xcassets 添加任何颜色,只需调用资源列表上的上下文菜单,然后“新建颜色集”即可!您可以将其与 Interface Builder 或以编程方式一起使用。

【讨论】:

您能解释一下如何精确地“以编程方式”执行此操作吗?这会增加其他答案吗? 你可以这样初始化UIColor(named: "nameOfYourRecource")

以上是关于如何在 iOS/xcode 中重用颜色和样式?的主要内容,如果未能解决你的问题,请参考以下文章

可重用的.xib + 可可类组件,如何在情节提要中自动调整大小和样式?

iOS xcode重用tableview [关闭]

如何使用打字稿在可重用组件中导入html样式属性?

IOS Xcode中的样式按钮

如何使用多个选择器重用相同的样式规则

如何在android中为不同颜色的按钮重用选择器?