首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift @IBDesignable - @IBInspectable多变量

Swift @IBDesignable - @IBInspectable多变量
EN

Stack Overflow用户
提问于 2016-08-10 20:07:56
回答 1查看 2.2K关注 0票数 3

我正在尝试为UILabel创建一个自定义类,这样我就可以从故事板中看到结果。为了创建大纲标签,我需要更改文本属性。

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

如果我有多个var,我会得到以下错误。

代码语言:javascript
复制
> '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

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

代码语言:javascript
复制
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)

        }
    }



}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-10 20:19:06

正如我在注释中所说的--您需要将每个变量放在单独的行中。这意味着您需要为它们声明didSet。如下所示:

代码语言:javascript
复制
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)
    }

}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38873034

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档