Search code examples
iosswift2ibdesignable

Swift @IBDesignable - @IBInspectable multiple variables


I am trying to create a custom class for UILabel so I can see the result from the Storyboard. I need to change the text attributes in order to create an outline label.

With the code I have so far I can manage to do this however I can only add one variable.

If I had multiple var I get the following errors.

> '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

How can I use multiple variables? CODE:

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)

        }
    }



}

Solution

  • As I said in the comment - you need to have each variable in separate lines. This means that you need to have didSet declared for both of them. Something like this :

    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)
        }
    
    }