Swift @IBDesignable - @IBInspectable 多个变量

3

我试图为 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)

        }
    }



}

只需将它们放在单独的行中,并根据需要进行注释。 - Losiowaty
1个回答

3

正如我在评论中所说,您需要将每个变量单独放在一行中。这意味着您需要为两个变量都声明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 - SNos
复制粘贴不起作用了。编写代码完美运行。 - SNos
为什么如果我在代码中更新文本,文本属性就不会被保存? - SNos
1
很难在没有看到代码的情况下确定 ;) 但你必须记住,textattributedTextUILabel的不同属性。这基本上意味着每次您想要设置新文本并保留属性时,都需要使用它们创建新的NSAttributedString - Losiowaty
谢谢。为了改变新字符串的文本属性,我必须在调用setAttributes函数之后调用。 - SNos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接