属性
获取父控制器
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() })
}
}
资源来自网络和日常整理,持续更新