UIViewExtension:圆角以及添加手势
2018-11-06 本文已影响0人
CN_HarrySun
1. 圆角
// MARK: - 圆角
extension UIView {
/**
Rounds the given set of corners to the specified radius
- parameter corners: Corners to round
- parameter radius: Radius to round to
*/
func round(corners: UIRectCorner, radius: CGFloat) {
_ = _round(corners: corners, radius: radius)
}
/**
Rounds the given set of corners to the specified radius with a border
- parameter corners: Corners to round
- parameter radius: Radius to round to
- parameter borderColor: The border color
- parameter borderWidth: The border width
*/
func round(corners: UIRectCorner, radius: CGFloat, borderColor: UIColor, borderWidth: CGFloat) {
let mask = _round(corners: corners, radius: radius)
addBorder(mask: mask, borderColor: borderColor, borderWidth: borderWidth)
}
/**
Fully rounds an autolayout view (e.g. one with no known frame) with the given diameter and border
- parameter diameter: The view's diameter
- parameter borderColor: The border color
- parameter borderWidth: The border width
*/
func fullyRound(diameter: CGFloat, borderColor: UIColor, borderWidth: CGFloat) {
layer.masksToBounds = true
layer.cornerRadius = diameter / 2
layer.borderWidth = borderWidth
layer.borderColor = borderColor.cgColor;
}
}
private extension UIView {
@discardableResult func _round(corners: UIRectCorner, radius: CGFloat) -> CAShapeLayer {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
return mask
}
func addBorder(mask: CAShapeLayer, borderColor: UIColor, borderWidth: CGFloat) {
let borderLayer = CAShapeLayer()
borderLayer.path = mask.path
borderLayer.fillColor = UIColor.clear.cgColor
borderLayer.strokeColor = borderColor.cgColor
borderLayer.lineWidth = borderWidth
borderLayer.frame = bounds
layer.addSublayer(borderLayer)
}
}
2. 圆角使用
// 仅右上侧和右下侧圆角
view.round(corners: [.topRight, .bottomRight], radius: 6)
// 所有圆角
view.round(corners: .allCorners, radius: 6)
3. 手势扩展(Rx版)
// MARK: - 手势扩展
extension UIView {
func addTapAction(target: Any, action: Selector) {
self.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: target, action: action)
self.addGestureRecognizer(tap)
}
func addTapAction() -> Driver<UITapGestureRecognizer> {
self.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer()
self.addGestureRecognizer(tap)
return tap.rx.event.asDriver()
}
func addSwipeAction(direction: UISwipeGestureRecognizerDirection = .up) -> Driver<UISwipeGestureRecognizer> {
self.isUserInteractionEnabled = true
let recognizer = UISwipeGestureRecognizer()
recognizer.direction = direction
addGestureRecognizer(recognizer)
return recognizer.rx.event.asDriver()
}
}
4. 手势扩展使用(Rx版)
view.addTapAction()
.drive(onNext: { _ in
print("view tap")
})
.disposed(by: self.disposeBag)