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

前端之家收集整理的这篇文章主要介绍了如何重用iOS / xcode中的颜色和样式?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Android,WPF以及我一直在使用的大多数平台都有办法在单个文件中重用和“集中”ui资源,如颜色和样式.

在android中它可以这样做:

在colors.xml文件中:

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

在任何视图中:

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

iOS中有类似的东西吗?

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

我遇到的唯一一件事就是在代码中定义Theme,并在代码中重用它,这是正确的方法吗?

解决方法

您可以使用任何单例类或UIColor扩展来完成此操作.以下是UIColor扩展示例.
  1. import Foundation
  2. import UIKit
  3.  
  4. extension UIColor
  5. {
  6. class func someColor1() -> UIColor
  7. {
  8. return UIColor(red: 123.0/255.0,green: 162.0/255.0,blue: 157.0/255.0,alpha:1.0)
  9. }
  10.  
  11. class func someColor2() -> UIColor
  12. {
  13. return UIColor(red: 154.0/255.0,green: 143.0/255.0,blue: 169.0/255.0,alpha:1.0)
  14. }
  15. }

稍后您可以访问颜色

  1. textField.textColor = UIColor.someColor2()

编辑:
您也可以使用NSAttributedString对样式执行相同的操作

  1. class StyleHelper : NSObject{
  2.  
  3. class func getSecondaryTextWithString(textString:String) -> NSAttributedString
  4. {
  5. let secondaryTextStyleAttributes: [String : AnyObject] = [
  6. NSForegroundColorAttributeName: UIColor.greenColor(),NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleDouble.rawValue,NSFontAttributeName: UIFont.systemFontOfSize(14.0)]
  7. let secondaryTextStyleString = NSAttributedString(string: textString,attributes:secondaryTextStyleAttributes)
  8. return secondaryTextStyleString
  9. }
  10. }

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

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

猜你在找的iOS相关文章