112 lines
3.1 KiB
Swift
112 lines
3.1 KiB
Swift
//
|
|
// UIView+SPAdd.swift
|
|
// ShortPlay
|
|
//
|
|
// Created by 曾觉新 on 2025/4/9.
|
|
//
|
|
|
|
import UIKit
|
|
import SnapKit
|
|
|
|
extension UIView {
|
|
fileprivate struct AssociatedKeys {
|
|
static var sp_tapGesture: Int?
|
|
static var sp_effect: Int?
|
|
static var sp_circulars: Int?
|
|
}
|
|
@objc public static func sp_Awake() {
|
|
sp_swizzled_instanceMethod("sp", oldClass: self, oldSelector: "layoutSubviews", newClass: self)
|
|
}
|
|
|
|
@objc func sp_layoutSubviews() {
|
|
sp_layoutSubviews()
|
|
_updateRadius()
|
|
|
|
if let effectView = effectView, effectView.frame != self.bounds {
|
|
effectView.frame = self.bounds
|
|
}
|
|
}
|
|
|
|
///获得当前的响应视图
|
|
func getFirstResponderView() -> UIView? {
|
|
var resultView: UIView? = nil
|
|
|
|
for view in self.subviews {
|
|
if view.isFirstResponder {
|
|
resultView = view
|
|
break
|
|
} else {
|
|
resultView = view.getFirstResponderView()
|
|
if resultView != nil {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
return resultView
|
|
}
|
|
}
|
|
|
|
|
|
//MARK: -------------- 模糊效果 --------------
|
|
extension UIView {
|
|
private var effectView: UIVisualEffectView? {
|
|
get {
|
|
return objc_getAssociatedObject(self, &AssociatedKeys.sp_effect) as? UIVisualEffectView
|
|
}
|
|
set {
|
|
objc_setAssociatedObject(self, &AssociatedKeys.sp_effect, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
|
|
}
|
|
}
|
|
|
|
///添加模糊效果
|
|
func addEffectView(style: UIBlurEffect.Style = .dark) {
|
|
if self.effectView == nil {
|
|
let blur = UIBlurEffect(style: style)
|
|
let effectView = UIVisualEffectView(effect: blur)
|
|
self.addSubview(effectView)
|
|
self.sendSubviewToBack(effectView)
|
|
|
|
self.effectView = effectView
|
|
}
|
|
}
|
|
///删除模糊效果
|
|
func removeEffectView() {
|
|
self.effectView?.removeFromSuperview()
|
|
self.effectView = nil
|
|
}
|
|
}
|
|
|
|
//MARK: -------------- 圆角 --------------
|
|
extension UIView {
|
|
|
|
|
|
private var circulars: SPCirculars? {
|
|
get {
|
|
return objc_getAssociatedObject(self, &AssociatedKeys.sp_circulars) as? SPCirculars
|
|
}
|
|
set {
|
|
objc_setAssociatedObject(self, &AssociatedKeys.sp_circulars, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
|
|
}
|
|
}
|
|
|
|
func addRadius(topLeft: CGFloat, topRight: CGFloat, bottomLeft: CGFloat, bottomRight: CGFloat) {
|
|
//清空其它设置方法
|
|
self.circulars = SPCirculars(topLeft: topLeft, topRight: topRight, bottomLeft: bottomLeft, bottomRight: bottomRight)
|
|
_updateRadius()
|
|
}
|
|
|
|
private func _updateRadius() {
|
|
guard let circulars = self.circulars else { return }
|
|
let rect = self.bounds
|
|
|
|
let path = CGMutablePath()
|
|
path.addRadiusRectangle(circulars, rect: rect)
|
|
|
|
let maskLayer = CAShapeLayer()
|
|
maskLayer.frame = self.bounds
|
|
maskLayer.path = path
|
|
self.layer.mask = maskLayer
|
|
}
|
|
|
|
}
|