如何在Swift中实现OC中的分类?using Swift Extensions as OC categories

分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友 微信微信
查看查看222 回复回复4 收藏收藏 分享淘帖 转播转播 分享分享 微信
查看: 222|回复: 4
收起左侧

如何在Swift中实现OC中的分类?using Swift Extensions as OC categories

[复制链接]
代码买卖 发表于 2016-8-28 22:41:48 | 显示全部楼层 |阅读模式
快来登录
获取优质的苹果资讯内容
收藏热门的iOS等技术干货
拷贝下载Swift Demo源代码
订阅梳理好了的知识点专辑

在OC中为了增强已有类的功能,我们经常使用分类。使用分类,我们可以在不破坏原有类的结构的前提下,对原有类进行模块化的扩展。

但是在Swift中没有分类这种写法了。相对应的是Swift中只有扩展(Extensions)。

下面是Swift中扩展(Extensions)的说明:

扩展就是向一个已有的类、结构体、枚举类型或者协议类型添加新功能(functionality)。这包括在没有权限获取原始源代码的情况下扩展类型的能力(即逆向建模)。扩展和 Objective-C 中的分类(categories)类似。(不过与 Objective-C 不同的是,Swift 的扩展没有名字。)


那么我们怎么在Swift中实现OC中的分类呢?我们可以向苹果学习。

同样是UIView类,我们分别看看OC和Swift不同的实现方式。




1、我们先看看OC中的UIView

这是 UIView中的声明的代码:

[Objective-C] 纯文本查看 复制代码
#ifndef SDK_HIDE_TIDE
NS_CLASS_AVAILABLE_IOS(2_0) @interface UIView : UIResponder <NSCoding, UIAppearance, UIAppearanceContainer, UIDynamicItem, UITraitEnvironment, UICoordinateSpace, UIFocusEnvironment>
#else
NS_CLASS_AVAILABLE_IOS(2_0) @interface UIView : UIResponder <NSCoding, UIAppearance, UIAppearanceContainer, UIDynamicItem, UITraitEnvironment, UICoordinateSpace>
#endif

+ (Class)layerClass;                        // default is [CALayer class]. Used when creating the underlying layer for the view.

- (instancetype)initWithFrame:(CGRect)frame NS_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;

@property(nonatomic,getter=isUserInteractionEnabled) BOOL userInteractionEnabled;  // default is YES. if set to NO, user events (touch, keys) are ignored and removed from the event queue.
@property(nonatomic)                                 NSInteger tag;                // default is 0
@property(nonatomic,readonly,strong)                 CALayer  *layer;              // returns view's layer. Will always return a non-nil value. view is layer's delegate

#ifndef SDK_HIDE_TIDE
- (BOOL)canBecomeFocused NS_AVAILABLE_IOS(9_0); // NO by default
@property (readonly, nonatomic, getter=isFocused) BOOL focused NS_AVAILABLE_IOS(9_0);
#endif
+ (UIUserInterfaceLayoutDirection)userInterfaceLayoutDirectionForSemanticContentAttribute:(UISemanticContentAttribute)attribute NS_AVAILABLE_IOS(9_0);
@property (nonatomic) UISemanticContentAttribute semanticContentAttribute NS_AVAILABLE_IOS(9_0);
@end


其他的属性和方法都是使用分类的方式进行扩展的。

下面是页面渲染相关的属性和方法:

[Objective-C] 纯文本查看 复制代码
@interface UIView(UIViewRendering)

- (void)drawRect:(CGRect)rect;

- (void)setNeedsDisplay;
- (void)setNeedsDisplayInRect:(CGRect)rect;

@property(nonatomic)                 BOOL              clipsToBounds;              // When YES, content and subviews are clipped to the bounds of the view. Default is NO.
@property(nullable, nonatomic,copy)            UIColor          *backgroundColor UI_APPEARANCE_SELECTOR; // default is nil. Can be useful with the appearance proxy on custom UIView subclasses.
@property(nonatomic)                 CGFloat           alpha;                      // animatable. default is 1.0
@property(nonatomic,getter=isOpaque) BOOL              opaque;                     // default is YES. opaque views must fill their entire bounds or the results are undefined. the active CGContext in drawRect: will not have been cleared and may have non-zeroed pixels
@property(nonatomic)                 BOOL              clearsContextBeforeDrawing; // default is YES. ignored for opaque views. for non-opaque views causes the active CGContext in drawRect: to be pre-filled with transparent pixels
@property(nonatomic,getter=isHidden) BOOL              hidden;                     // default is NO. doesn't check superviews
@property(nonatomic)                 UIViewContentMode contentMode;                // default is UIViewContentModeScaleToFill
@property(nonatomic)                 CGRect            contentStretch NS_DEPRECATED_IOS(3_0,6_0) __TVOS_PROHIBITED; // animatable. default is unit rectangle {{0,0} {1,1}}. Now deprecated: please use -[UIImage resizableImageWithCapInsets:] to achieve the same effect.

@property(nullable, nonatomic,strong)          UIView           *maskView NS_AVAILABLE_IOS(8_0);

/*
 -tintColor always returns a color. The color returned is the first non-default value in the receiver's superview chain (starting with itself).
 If no non-default value is found, a system-defined color is returned.
 If this view's -tintAdjustmentMode returns Dimmed, then the color that is returned for -tintColor will automatically be dimmed.
 If your view subclass uses tintColor in its rendering, override -tintColorDidChange in order to refresh the rendering if the color changes.
 */
@property(null_resettable, nonatomic, strong) UIColor *tintColor NS_AVAILABLE_IOS(7_0);

/*
 -tintAdjustmentMode always returns either UIViewTintAdjustmentModeNormal or UIViewTintAdjustmentModeDimmed. The value returned is the first non-default value in the receiver's superview chain (starting with itself).
 If no non-default value is found, UIViewTintAdjustmentModeNormal is returned.
 When tintAdjustmentMode has a value of UIViewTintAdjustmentModeDimmed for a view, the color it returns from tintColor will be modified to give a dimmed appearance.
 When the tintAdjustmentMode of a view changes (either the view's value changing or by one of its superview's values changing), -tintColorDidChange will be called to allow the view to refresh its rendering.
 */
@property(nonatomic) UIViewTintAdjustmentMode tintAdjustmentMode NS_AVAILABLE_IOS(7_0);

/*
 The -tintColorDidChange message is sent to appropriate subviews of a view when its tintColor is changed by client code or to subviews in the view hierarchy of a view whose tintColor is implicitly changed when its superview or tintAdjustmentMode changes.
 */
- (void)tintColorDidChange NS_AVAILABLE_IOS(7_0);

@end





2、再来看看Swift中的代码

UIView类中的声明:

[Swift] 纯文本查看 复制代码
@available(iOS 2.0, *)
    public class UIView : UIResponder, NSCoding, UIAppearance, UIAppearanceContainer, UIDynamicItem, UITraitEnvironment, UICoordinateSpace, UIFocusEnvironment {

    public class func layerClass() -> AnyClass // default is [CALayer class]. Used when creating the underlying layer for the view.

    public init(frame: CGRect)
    public init?(coder aDecoder: NSCoder)

    public var userInteractionEnabled: Bool // default is YES. if set to NO, user events (touch, keys) are ignored and removed from the event queue.
    public var tag: Int // default is 0
    public var layer: CALayer { get } // returns view's layer. Will always return a non-nil value. view is layer's delegate

    @available(iOS 9.0, *)
    public func canBecomeFocused() -> Bool // NO by default
    @available(iOS 9.0, *)
    public var focused: Bool { get }

    @available(iOS 9.0, *)
    public class func userInterfaceLayoutDirectionForSemanticContentAttribute(attribute: UISemanticContentAttribute) -> UIUserInterfaceLayoutDirection
    @available(iOS 9.0, *)
    public var semanticContentAttribute: UISemanticContentAttribute
}


页面渲染的代码:

[Swift] 纯文本查看 复制代码
extension UIView {

    public func drawRect(rect: CGRect)

    public func setNeedsDisplay()
    public func setNeedsDisplayInRect(rect: CGRect)

    public var clipsToBounds: Bool // When YES, content and subviews are clipped to the bounds of the view. Default is NO.
    @NSCopying public var backgroundColor: UIColor? // default is nil. Can be useful with the appearance proxy on custom UIView subclasses.
    public var alpha: CGFloat // animatable. default is 1.0
    public var opaque: Bool // default is YES. opaque views must fill their entire bounds or the results are undefined. the active CGContext in drawRect: will not have been cleared and may have non-zeroed pixels
    public var clearsContextBeforeDrawing: Bool // default is YES. ignored for opaque views. for non-opaque views causes the active CGContext in drawRect: to be pre-filled with transparent pixels
    public var hidden: Bool // default is NO. doesn't check superviews
    public var contentMode: UIViewContentMode // default is UIViewContentModeScaleToFill
    // animatable. default is unit rectangle {{0,0} {1,1}}. Now deprecated: please use -[UIImage resizableImageWithCapInsets:] to achieve the same effect.

    @available(iOS 8.0, *)
    public var maskView: UIView?

    /*
     -tintColor always returns a color. The color returned is the first non-default value in the receiver's superview chain (starting with itself).
     If no non-default value is found, a system-defined color is returned.
     If this view's -tintAdjustmentMode returns Dimmed, then the color that is returned for -tintColor will automatically be dimmed.
     If your view subclass uses tintColor in its rendering, override -tintColorDidChange in order to refresh the rendering if the color changes.
     */
    @available(iOS 7.0, *)
    public var tintColor: UIColor!

    /*
     -tintAdjustmentMode always returns either UIViewTintAdjustmentModeNormal or UIViewTintAdjustmentModeDimmed. The value returned is the first non-default value in the receiver's superview chain (starting with itself).
     If no non-default value is found, UIViewTintAdjustmentModeNormal is returned.
     When tintAdjustmentMode has a value of UIViewTintAdjustmentModeDimmed for a view, the color it returns from tintColor will be modified to give a dimmed appearance.
     When the tintAdjustmentMode of a view changes (either the view's value changing or by one of its superview's values changing), -tintColorDidChange will be called to allow the view to refresh its rendering.
     */
    @available(iOS 7.0, *)
    public var tintAdjustmentMode: UIViewTintAdjustmentMode

    /*
     The -tintColorDidChange message is sent to appropriate subviews of a view when its tintColor is changed by client code or to subviews in the view hierarchy of a view whose tintColor is implicitly changed when its superview or tintAdjustmentMode changes.
     */
    @available(iOS 7.0, *)
    public func tintColorDidChange()
}





3、创建我们自己的extension

下面就让我们尝试一下,写一个自己的Swift分类。

在get和set UIView的x和y属性的时候代码很繁琐,如下:

[Swift] 纯文本查看 复制代码
//get x
var x = self.view.frame.origin.x

//set x
var rect = self.view.frame
rect.origin.x = 100
self.view.frame = rect


我们希望这里的代码是这样的:

[Swift] 纯文本查看 复制代码
//get x
var x = self.view.x
//set x
self.view.x = 100


在OC中我们可以写一个分类来实现,这个难度不大。懒的自己写的可以参照这个:https://github.com/findM/UIView-Positioning

在Swift中我们需要写一个extension来实现。



3.1、新建Swift文件

如何在Swift中实现OC中的分类?

如何在Swift中实现OC中的分类?using Swift Extensions as OC categories - 敏捷大拇指 - 如何在Swift中实现OC中的分类?




3.2、代码实现

[Swift] 纯文本查看 复制代码
import Foundation
import UIKit

//private var PERSON_ID_NUMBER_PROPERTY = 0

extension UIView {
    public var x: CGFloat{
        get{
            return self.frame.origin.x
        }
        set{
            var r = self.frame
            r.origin.x = newValue
            self.frame = r
        }
    }
    public var y: CGFloat{
        get{
            return self.frame.origin.y
        }
        set{
            var r = self.frame
            r.origin.y = newValue
            self.frame = r
        }
    }
    //其他的篇幅原因就不在这里一一实现了
}



全部的实现方法请参考这里:https://github.com/findM/UIView-Positioning-Swift




作者:findM

都看到这里了,就把这篇资料推荐给您的好朋友吧,让他们也感受一下。

回帖是一种美德,也是对楼主发帖的尊重和支持。

*声明:敏捷大拇指是全球最大的Swift开发者社区、苹果粉丝家园、智能移动门户,所载内容仅限于传递更多最新信息,并不意味赞同其观点或证实其描述;内容仅供参考,并非绝对正确的建议。本站不对上述信息的真实性、合法性、完整性做出保证;转载请注明来源并加上本站链接,敏捷大拇指将保留所有法律权益。如有疑问或建议,邮件至marketing@swifthumb.com

*联系:微信公众平台:“swifthumb” / 腾讯微博:@swifthumb / 新浪微博:@swifthumb / 官方QQ一群:343549891(满) / 官方QQ二群:245285613 ,需要报上用户名才会被同意进群,请先注册敏捷大拇指

嗯,不错!期待更多好内容,支持一把:
支持敏捷大拇指,用支付宝支付10.24元 支持敏捷大拇指,用微信支付10.24元

评分

参与人数 1金钱 +10 贡献 +10 专家分 +10 收起 理由
Anewczs + 10 + 10 + 10 32个赞!专家给力!

查看全部评分

firefighter 发表于 2016-8-28 22:49:21 | 显示全部楼层
直接看源代码果然是个很棒的学习方法!
i0n1c 发表于 2016-8-28 23:08:52 | 显示全部楼层
不错~~~~
swifter 发表于 2016-8-29 14:44:24 | 显示全部楼层
Nice!
yadan 发表于 2016-8-29 15:45:46 | 显示全部楼层
扩展就是向一个已有的类、结构体、枚举类型或者协议类型添加新功能(functionality)!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

做任务,领红包。
我要发帖

分享扩散

都看到这里了,就把这资料推荐给您的好朋友吧,让他们也感受一下。
您的每一位朋友访问此永久链接后,您都将获得相应的金钱积分奖励
热门推荐

合作伙伴

Swift小苹果

  • 北京治世天下科技有限公司
  • ©2014-2016 敏捷大拇指
  • 京ICP备14029482号
  • Powered by Discuz! X3.1 Licensed
  • swifthumb Wechat Code
  •   
快速回复 返回顶部 返回列表