Swift @IBDesignable - @IBInspectable多个变量

时间:2016-08-10 12:07:56

标签: ios swift2 ibdesignable

我正在尝试为UILabel创建一个自定义类,以便我可以从Storyboard中看到结果。我需要更改文本属性才能创建轮廓标签。

使用我到目前为止的代码,我可以设法做到这一点,但我只能添加一个变量。

如果我有多个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

如何使用多个变量? 代码:

import UIKit

@IBDesignable
class CustomUILabel: UILabel {
    @IBInspectable var outlineWidth: CGFloat = 1.0, var outlineColor = UIColor.whiteColor() {
        didSet {


                let strokeTextAttributes = [
                    NSStrokeColorAttributeName : outlineColor,
                    NSStrokeWidthAttributeName : -1 * outlineWidth,
                    ]

                self.attributedText = NSAttributedString(string: self.text ?? "", attributes: strokeTextAttributes)

        }
    }



}

1 个答案:

答案 0 :(得分:2)

正如我在评论中所说 - 你需要将每个变量放在不同的行中。这意味着您需要为它们两者声明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)
    }

}