1
我正在研究一項功能,可以在UILabel上設置自定義樣式(通過貼上樣式名稱)。我對此有一個簡單的代碼:iOS @IBDesignable autorefresh UILabel params as title,font,color
struct Style {
var fontName: String!
var fontSize: CGFloat!
var color: UIColor!
var styleName: String!
var font: UIFont {
return UIFont(name: self.fontName, size: self.fontSize)!
}
init(styleName: String, fontName: String!, fontSize: CGFloat!, color: UIColor!) {
self.fontName = fontName
self.fontSize = fontSize
self.color = color
}
var desc: String {
return "Style: \(styleName)"
}
}
let dictStyle: [String: Style] = [
"normal": Style(styleName: "normal", fontName: "HelveticaNeue-Light", fontSize: 20, color: UIColor.red),
"bold": Style(styleName: "bold", fontName: "HelveticaNeue-Bold", fontSize: 30, color: UIColor.black)
]
@IBDesignable class Label: UILabel {
@IBInspectable var style: String = "normal" {
didSet {
setNeedsDisplay()
}
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
self.text = "\(style)" // there is normal or bold
if let color = dictStyle[self.style]?.color {
self.textColor = color
}
if let font = dictStyle[self.style]?.font {
self.font = font
}
if let name = dictStyle[self.style]?.styleName {
self.text = name
}
}
}
,它的工作好,但我想自動更改標題,字體,顏色在Interface Builder(以下紅色矩形)。
我見過.storyboard文件
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="9lO-cw-I2Z" customClass="Label" customModule="AutoRefresh" customModuleProvider="target">
<rect key="frame" x="24" y="44" width="327" height="24"/>
<fontDescription key="fontDescription" name="HelveticaNeue" family="Helvetica Neue" pointSize="32"/>
<color key="textColor" red="0.25098040700000002" green="0.50196081400000003" blue="0.0" alpha="0.76206656679999996" colorSpace="calibratedRGB"/>
<nil key="highlightedColor"/>
<userDefinedRuntimeAttributes>
<userDefinedRuntimeAttribute type="string" keyPath="style" value="normal"/>
</userDefinedRuntimeAttributes>
</label>
所以爲 「文本」 或 「文字顏色」 字段不會改變。