1
import Foundation
import UIKit
extension UIImage {
/// Returns a image that fills in newSize
func resizedImage(newSize: CGSize) -> UIImage {
// Guard newSize is different
guard self.size != newSize else { return self }
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
/// Returns a resized image that fits in rectSize, keeping it's aspect ratio
/// Note that the new image size is not rectSize, but within it.
func resizedImageWithinRect(rectSize: CGSize) -> UIImage {
let widthFactor = size.width / rectSize.width
let heightFactor = size.height / rectSize.height
var resizeFactor = widthFactor
if size.height > size.width {
resizeFactor = heightFactor
}
let newSize = CGSize(width: size.width/resizeFactor, height: size.height/resizeFactor)
let resized = resizedImage(newSize: newSize)
return resized
}
}
2
import Foundation
extension Array {
mutating func moveToTop(at index: Int) {
rearrange(from: index, to: 0)
}
mutating func rearrange(from index1: Int, to index2: Int) {
if index1 >= self.count || index2 >= self.count {
return
}
insert(remove(at: index1), at: index2)
}
}
3
import Foundation
import UIKit
// MARK: - Convenience methods for UIView
public extension UIView {
convenience init(color: UIColor) {
self.init()
backgroundColor = color
}
func clipsToBoundsAndRasterize() {
clipsToBounds = true
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
}
func addBottomBorderWithColor(color: UIColor, width: CGFloat) {
let view = UIView()
view.backgroundColor = color
self.addSubview(view)
view.snp.makeConstraints { (make) in
make.width.equalToSuperview()
make.height.equalTo(width)
make.bottom.equalToSuperview()
make.left.equalToSuperview()
}
}
func with(color: UIColor) -> Self {
backgroundColor = color
return self
}
func with(radius: CGFloat) -> Self {
layer.cornerRadius = radius
return self
}
// add corner to a corner
// if using autolayout call it in layoutSubviews
// view.roundCorners([.topLeft, .bottomRight], radius: 10)
func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: bounds,
byRoundingCorners: corners,
cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
}
}