美文网首页
Swift中类的分类写法

Swift中类的分类写法

作者: kuxiu | 来源:发表于2016-07-08 11:41 被阅读104次

    1.创建一个swift文件

    h1 命名可以按照OC的习惯命名,例如UIView+Extension


    图例1png

    2.分类实现,如下UIView的分类写法书写

    import Foundation
    import UIKit
    
    extension UIView
    {
        public var x:CGFloat
            {
            get{
                return self.frame.origin.x
            }
            
            set{
                var frame = self.frame
                frame.origin.x = x
                self.frame = frame
            }
        }
        
        public var y:CGFloat
            {
            get{
                return self.frame.origin.y
            }
            set{
                var frame = self.frame
                frame.origin.y = y
                self.frame = frame
            }
        }
        
        public var width:CGFloat
            {
            get{
                return self.frame.size.width
            }
            set{
                var frame = self.frame
                frame.size.width = width
                self.frame = frame
            }
        }
        
        public var height:CGFloat
            {
            get{
                return self.frame.size.height
            }
            set{
                var frame = self.frame
                frame.size.height = height
                self.frame = frame
            }
        }
        
        public var centerX:CGFloat
            {
            get{
                return self.center.x
            }
            set{
                var center = self.center
                center.x = centerX
                self.center = center
            }
        }
        
        public var centerY :CGFloat
            {
            get{
                return self.center.y
            }
            set{
                var center = self.center
                center.y = centerY
                self.center = center
            }
        }
        
        public var size:CGSize
            {
            get{
                return self.frame.size
            }
            set{
                var tempFrame = self.frame
                tempFrame.size = size
                self.frame = tempFrame
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:Swift中类的分类写法

          本文链接:https://www.haomeiwen.com/subject/ootrjttx.html