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
}
}
需要样式时,您会打电话给
someLabel.attributedText = StyleHelper.getSecondaryTextWithString("SomeText")