美文网首页Swift
Swift-UIView Extension

Swift-UIView Extension

作者: 长风浮云 | 来源:发表于2018-05-15 14:43 被阅读0次

    属性

    获取父控制器

    extension UIView {
         public var parentViewController: UIViewController? {
            weak var parentResponder: UIResponder? = self
            while parentResponder != nil {
                parentResponder = parentResponder!.next
                if let viewController = parentResponder as? UIViewController {
                    return viewController
                }
            }
            return nil
        }
    }
    

    size

    extension UIView {
         public var size: CGSize {
            get {
                return frame.size
            }
            set {
                width = newValue.width
                height = newValue.height
            }
        }
    }
    

    height

    extension UIView {
         public var height: CGFloat {
            get {
                return frame.size.height
            }
            set {
                frame.size.height = newValue
            }
        }
    }
    

    width

    extension UIView {
         public var width: CGFloat {
            get {
                return frame.size.width
            }
            set {
                frame.size.width = newValue
            }
        }
    }
    

    x

    extension UIView {
         public var x: CGFloat {
            get {
                return frame.origin.x
            }
            set {
                frame.origin.x = newValue
            }
        }
    }
    

    y

    extension UIView {
         public var y: CGFloat {
            get {
                return frame.origin.y
            }
            set {
                frame.origin.y = newValue
            }
        }
    }
    

    方法

    第一响应者

    extension UIView {
         public func firstResponder() -> UIView? {
            var views = [UIView](arrayLiteral: self)
            var i = 0
            repeat {
                let view = views[i]
                if view.isFirstResponder {
                    return view
                }
                views.append(contentsOf: view.subviews)
                i += 1
            } while i < views.count
            return nil
        }
    }
    

    添加多个子视图

    extension UIView {
       public func addSubviews(_ subviews: [UIView]) {
           subviews.forEach({ self.addSubview($0) })
       }
       
       public func removeSubviews() {
           subviews.forEach({ $0.removeFromSuperview() })
       }
    }
    

    资源来自网络和日常整理,持续更新

    相关文章

      网友评论

        本文标题:Swift-UIView Extension

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