如何在swift中實(shí)現(xiàn)oc中的分類

在oc中為了增強(qiáng)已有類的功能炼邀,我們經(jīng)常使用分類讶舰。使用分類捞蚂,我們可以在不破壞原有類的結(jié)構(gòu)的前提下妇押,對(duì)原有類進(jìn)行模塊化的擴(kuò)展。

但是在swift中沒(méi)有分類這種寫法了姓迅。相對(duì)應(yīng)的是swift中只有擴(kuò)展(Extensions)敲霍。

下面是swift中擴(kuò)展(Extensions)的說(shuō)明

擴(kuò)展就是向一個(gè)已有的類、結(jié)構(gòu)體丁存、枚舉類型或者協(xié)議類型添加新功能(functionality)肩杈。這包括在沒(méi)有權(quán)限獲取原始源代碼的情況下擴(kuò)展類型的能力(即逆向建模)。擴(kuò)展和 Objective-C 中的分類(categories)類似解寝。(不過(guò)與 Objective-C 不同的是扩然,Swift 的擴(kuò)展沒(méi)有名字。)

那么我們?cè)趺丛趕wift中實(shí)現(xiàn)oc中的分類呢聋伦?我們可以向蘋果學(xué)習(xí)夫偶。
同樣是UIView類,我們分別看看oc和swift不同的實(shí)現(xiàn)方式觉增。

1.我們先看看oc中的UIView

這是 UIView中的聲明的代碼

#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

其他的屬性和方法都是使用分類的方式進(jìn)行擴(kuò)展的兵拢。
下面是頁(yè)面渲染相關(guān)的屬性和方法

@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類中的聲明

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

頁(yè)面渲染的代碼

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.創(chuàng)建我們自己的extension

下面就讓我們嘗試一下,寫一個(gè)自己的swift分類
在get和set UIView的x和y屬性的時(shí)候代碼很繁瑣逾礁,如下:

//get x
var x = self.view.frame.origin.x

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

我們希望這里的代碼是這樣的

//get x
var x = self.view.x
//set x
self.view.x = 100

在oc中我們可以寫一個(gè)分類來(lái)實(shí)現(xiàn)说铃,這個(gè)難度不大。懶的自己寫的可以參照這個(gè)https://github.com/findM/UIView-Positioning
在swift中我們需要寫一個(gè)extension來(lái)實(shí)現(xiàn)
3.1 新建swift文件

新建swift文件.png

3.2 代碼實(shí)現(xiàn)

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
        }
    }
    //其他的篇幅原因就不在這里一一實(shí)現(xiàn)了
}

全部的實(shí)現(xiàn)方法請(qǐng)參考這里https://github.com/findM/UIView-Positioning-Swift

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市截汪,隨后出現(xiàn)的幾起案子疾牲,更是在濱河造成了極大的恐慌,老刑警劉巖衙解,帶你破解...
    沈念sama閱讀 206,126評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件阳柔,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡蚓峦,警方通過(guò)查閱死者的電腦和手機(jī)舌剂,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,254評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)暑椰,“玉大人霍转,你說(shuō)我怎么就攤上這事∫黄” “怎么了避消?”我有些...
    開封第一講書人閱讀 152,445評(píng)論 0 341
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)召夹。 經(jīng)常有香客問(wèn)我岩喷,道長(zhǎng),這世上最難降的妖魔是什么监憎? 我笑而不...
    開封第一講書人閱讀 55,185評(píng)論 1 278
  • 正文 為了忘掉前任纱意,我火速辦了婚禮,結(jié)果婚禮上鲸阔,老公的妹妹穿的比我還像新娘偷霉。我一直安慰自己,他們只是感情好褐筛,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,178評(píng)論 5 371
  • 文/花漫 我一把揭開白布类少。 她就那樣靜靜地躺著,像睡著了一般死讹。 火紅的嫁衣襯著肌膚如雪瞒滴。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 48,970評(píng)論 1 284
  • 那天赞警,我揣著相機(jī)與錄音妓忍,去河邊找鬼。 笑死愧旦,一個(gè)胖子當(dāng)著我的面吹牛世剖,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播笤虫,決...
    沈念sama閱讀 38,276評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼旁瘫,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼祖凫!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起酬凳,我...
    開封第一講書人閱讀 36,927評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤惠况,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后宁仔,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體稠屠,經(jīng)...
    沈念sama閱讀 43,400評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,883評(píng)論 2 323
  • 正文 我和宋清朗相戀三年翎苫,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了权埠。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 37,997評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡煎谍,死狀恐怖攘蔽,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情呐粘,我是刑警寧澤满俗,帶...
    沈念sama閱讀 33,646評(píng)論 4 322
  • 正文 年R本政府宣布,位于F島的核電站作岖,受9級(jí)特大地震影響漫雷,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜鳍咱,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,213評(píng)論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望与柑。 院中可真熱鬧谤辜,春花似錦、人聲如沸价捧。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,204評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)结蟋。三九已至脯倚,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間嵌屎,已是汗流浹背推正。 一陣腳步聲響...
    開封第一講書人閱讀 31,423評(píng)論 1 260
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留宝惰,地道東北人植榕。 一個(gè)月前我還...
    沈念sama閱讀 45,423評(píng)論 2 352
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像尼夺,于是被迫代替她去往敵國(guó)和親尊残。 傳聞我的和親對(duì)象是個(gè)殘疾皇子炒瘸,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,722評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)、插件寝衫、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,022評(píng)論 4 62
  • 如置身大海中的茫茫黑夜 我把自己變成船 可沒(méi)有岸 也沒(méi)有星光 安靜又兇猛的潮水要將一切撕裂 很久以前顷扩,我總是說(shuō)很久...
    蔣菱閱讀 189評(píng)論 0 0
  • 醉過(guò)方知酒濃隘截,愛(ài)過(guò)方知情重。 01 在那個(gè)文化燦爛的民國(guó)歷史中事富,眾多文人墨客技俐,才子才女依次粉墨登場(chǎng),如果說(shuō)把才子佳...
    Soul麥芽閱讀 11,924評(píng)論 122 172
  • 今天實(shí)現(xiàn)一個(gè)類似微信的對(duì)話框練手统台,也算是新手入門雕擂,UI的編程伴隨很多繁瑣的問(wèn)題,記錄在這里贱勃。 問(wèn)題一:實(shí)現(xiàn)點(diǎn)擊輸入...
    雨如注閱讀 1,615評(píng)論 0 3