ephilip ephilip - 6 months ago 21
iOS Question

UIAppearance and Rounded Borders in Swift

So I'm fairly new to the whole UIAppearance approach to doing things, and doing it with swift. Hurray for not a ton of documentation out there.

I'm trying to set my border radius through UIAppearance with something along the lines of:

CircleButton.appearance.roundBorderRadius = 9


My CircleButton class implementation:

public class CircleButton : UIButton{
@nonobjc var roundBorderRadius: CGFloat? {
get { return self.layer.cornerRadius }
set {
self.layer.cornerRadius = newValue!
}
}
}


And I hook everything up in Storyboard to a ViewController that contains a CircleButton. No Compilation or Build errors.

However, at runtime I'm getting a:

"Thread 1: EXC_BAD_ACCESS" error on:

CircleButton.appearance.roundBorderRadius = 9


Any advice?

Answer

Remove @nonobjc and add dynamic, then change the type from CGFloat? to CGFloat and remove the ! after newValue in the setter, like so:

public class CircleButton : UIButton {
    dynamic var roundBorderRadius: CGFloat {
        get { return self.layer.cornerRadius }
        set {
            self.layer.cornerRadius = newValue
        }
    }
}
Comments