2014/11/21

Add property by Extension in Swift

I have been using category (for example) to get a width of UIView object like this :
@implementation UIView (AddWidth)
-(float)width
{
    return self.frame.size.width;
}
@end
Then I obtain the width by only ‘myView.width’.
So I tried to do the same thing, and found the way to use Extension in Swift. So I made this :
extension UIView {
    func width() -> CGFloat {
        return self.frame.size.width
    }
}
Then I can access to the width like this :
myView.width()
Well? I don’t like the last parenthesis!

But I found you can set properties by Extension
extension UIView {
    var width: CGFloat {
        return self.frame.size.width
    }
}
Then I can write like this to access its width :
myView.width
This is really nice.

Develop | Comments(0) | Trackback(0)
Comment

管理者のみに表示