Last active
June 25, 2018 07:13
-
-
Save yashthaker7/ac05557835297279925a510ac98428fe to your computer and use it in GitHub Desktop.
Apply gradient to view + Corner radius particular side to view + Anchors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
extension UIView { | |
enum gradientType { | |
case vertical | |
case horizontal | |
case cross | |
} | |
func applyGradient(colors:[UIColor], type: gradientType) { | |
var endPoint: CGPoint! | |
switch (type) { | |
case .horizontal: | |
endPoint = CGPoint(x: 1, y: 0) | |
case .vertical: | |
endPoint = CGPoint(x: 0, y: 1) | |
case .cross: | |
endPoint = CGPoint(x: 1, y: 1) | |
} | |
self.layoutIfNeeded() | |
let gradientLayer = CAGradientLayer() | |
gradientLayer.frame = self.bounds | |
gradientLayer.colors = colors.map{ $0.cgColor} | |
gradientLayer.startPoint = CGPoint(x: 0, y: 0) | |
gradientLayer.endPoint = endPoint | |
//self.layer.addSublayer(gradientLayer) | |
self.layer.insertSublayer(gradientLayer, at: 0) | |
} | |
func roundCorners(_ corners: UIRectCorner, radius: CGFloat) { | |
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) | |
let mask = CAShapeLayer() | |
mask.path = path.cgPath | |
self.layer.mask = mask | |
} | |
// Anchors | |
public func fillSuperview() { | |
translatesAutoresizingMaskIntoConstraints = false | |
if let superview = superview { | |
leftAnchor.constraint(equalTo: superview.leftAnchor).isActive = true | |
rightAnchor.constraint(equalTo: superview.rightAnchor).isActive = true | |
topAnchor.constraint(equalTo: superview.topAnchor).isActive = true | |
bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true | |
} | |
} | |
public func anchorCenterXToSuperview(constant: CGFloat = 0) { | |
translatesAutoresizingMaskIntoConstraints = false | |
if let anchor = superview?.centerXAnchor { | |
centerXAnchor.constraint(equalTo: anchor, constant: constant).isActive = true | |
} | |
} | |
public func anchorCenterYToSuperview(constant: CGFloat = 0) { | |
translatesAutoresizingMaskIntoConstraints = false | |
if let anchor = superview?.centerYAnchor { | |
centerYAnchor.constraint(equalTo: anchor, constant: constant).isActive = true | |
} | |
} | |
public func anchorCenterSuperview() { | |
anchorCenterXToSuperview() | |
anchorCenterYToSuperview() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment