Ios Swift@IBDesignable-@IBInspectable多变量
我正在尝试为Ios Swift@IBDesignable-@IBInspectable多变量,ios,swift2,ibdesignable,Ios,Swift2,Ibdesignable,我正在尝试为UILabel创建一个自定义类,以便从情节提要中查看结果。我需要更改文本属性以创建大纲标签 使用到目前为止的代码,我可以做到这一点,但是我只能添加一个变量 如果我有多个var,我会得到以下错误 > 'var' declarations with multiple variables cannot have explicit > getters/setters 'var' cannot appear nested inside another 'var' or > '
UILabel
创建一个自定义类,以便从情节提要中查看结果。我需要更改文本属性以创建大纲标签
使用到目前为止的代码,我可以做到这一点,但是我只能添加一个变量
如果我有多个var
,我会得到以下错误
> 'var' declarations with multiple variables cannot have explicit
> getters/setters 'var' cannot appear nested inside another 'var' or
> 'let' pattern Getter/setter can only be defined for a single variable
如何使用多个变量?
代码:
正如我在评论中所说的,您需要将每个变量放在单独的行中。这意味着您需要为它们声明
didSet
。大概是这样的:
import UIKit
@IBDesignable
class CustomUILabel: UILabel {
@IBInspectable var outlineWidth: CGFloat = 1.0 {
didSet {
self.setAttributes(self.outlineColor, outlineWidth: self.outlineWidth)
}
}
@IBInspectable var outlineColor = UIColor.whiteColor() {
didSet {
self.setAttributes(self.outlineColor, outlineWidth: self.outlineWidth)
}
}
func setAttributes(outlineColor:UIColor, outlineWidth: CGFloat) {
let strokeTextAttributes = [
NSStrokeColorAttributeName : outlineColor,
NSStrokeWidthAttributeName : -1 * outlineWidth,
]
self.attributedText = NSAttributedString(string: self.text ?? "", attributes: strokeTextAttributes)
}
}
只需将它们放在单独的行中,并根据需要对每个行进行注释谢谢。。我已经尝试过了,但是,我只能在属性检查器中查看和更改
outlineWidth
。复制和粘贴不起作用。。编写代码很有效,为什么如果我更新代码中的文本,文本属性不会保存?如果没有看到一些代码,很难说;)但是您必须记住,text
和attributedText
是UILabel
的单独属性。这基本上意味着,每次要设置新文本并保留所需的属性时,都需要使用它们创建新的nsattributestring
。谢谢。。为了更改新字符串的文本属性,我必须在setAttributes函数之后调用它
import UIKit
@IBDesignable
class CustomUILabel: UILabel {
@IBInspectable var outlineWidth: CGFloat = 1.0 {
didSet {
self.setAttributes(self.outlineColor, outlineWidth: self.outlineWidth)
}
}
@IBInspectable var outlineColor = UIColor.whiteColor() {
didSet {
self.setAttributes(self.outlineColor, outlineWidth: self.outlineWidth)
}
}
func setAttributes(outlineColor:UIColor, outlineWidth: CGFloat) {
let strokeTextAttributes = [
NSStrokeColorAttributeName : outlineColor,
NSStrokeWidthAttributeName : -1 * outlineWidth,
]
self.attributedText = NSAttributedString(string: self.text ?? "", attributes: strokeTextAttributes)
}
}