String + Extension
extension String {
//MARK: - 计算年龄(self必须是“YYYY-MM-dd”格式的字符串)
func ageWithStringOfBirth() -> String {
let array = self.components(separatedBy: "-")
if array.count == 3 && array[0].toInt() > 0 && array[1].toInt() > 0 && array[2].toInt() > 0 {
let dateFormatter = DateFormatter.init()
dateFormatter.dateFormat = "YYYY-MM-dd"
// if let birthDate:Date = dateFormatter.date(from: self)!{
if let birthDate:Date = dateFormatter.date(from: self) {
// 出生日期转换 年月日
let components1 = (Calendar.current as NSCalendar).components([.day,.month,.year], from: birthDate);
let brithDateYear = components1.year;
let brithDateDay = components1.day;
let brithDateMonth = components1.month;
// 获取系统当前 年月日
let components2 = (Calendar.current as NSCalendar).components([.day,.month,.year], from: Date())
let currentDateYear = components2.year;
let currentDateDay = components2.day;
let currentDateMonth = components2.month;
// 计算年龄
var iAge = currentDateYear! - brithDateYear! - 1;
if ((currentDateMonth! > brithDateMonth!) || (currentDateMonth! == brithDateMonth! && currentDateDay! >= brithDateDay!)) {
iAge += 1;
}
return iAge.toString
}else {
return "0"
}
}else {
return "0"
}
}
//MARK: 清除字符串小数点末尾的0
func cleanDecimalPointZear() -> String {
let newStr = self as NSString
var s = NSString()
var offset = newStr.length - 1
while offset > 0 {
s = newStr.substring(with: NSMakeRange(offset, 1)) as NSString
if s.isEqual(to: "0") || s.isEqual(to: ".") {
offset -= 1
} else {
break
}
}
return newStr.substring(to: offset + 1)
}
//MARK:设置字符串属性
func attributedString(_ color:UIColor,fontSize:CGFloat) -> NSAttributedString {
let dic = [NSFontAttributeName:UIFont.systemFont(ofSize: fontSize),NSForegroundColorAttributeName:color]
return NSAttributedString(string: self, attributes: dic)
}
//MARK: - 判断是不是正确的手机号码
func isTelNumber()->Bool
{
let regex:NSRegularExpression
do {
regex = try NSRegularExpression(pattern: "^((13[0-9])|(147)|(15[^4,\\D])|(18[0-9])|(17[0-9]))\\d{8}$", options: NSRegularExpression.Options.caseInsensitive)
let matches = regex.matches(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion , range: NSMakeRange(0, self.characters.count))
if matches.count > 0 { return true }
else { return false }
}
catch{
return false
}
}
//MARK: - 判断是不是身份证号码
func isIDNumber()->Bool
{
let regex:NSRegularExpression
do {
regex = try NSRegularExpression(pattern: "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X|x)$", options: NSRegularExpression.Options.caseInsensitive)
// regex = try NSRegularExpression(pattern: "^(\\d{14}|\\d{17})(\\d|[xX])$", options: NSRegularExpressionOptions.CaseInsensitive)
let matches = regex.matches(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion , range: NSMakeRange(0, self.characters.count))
if matches.count > 0 { return true }
else { return false }
}
catch{
return false
}
}
//
subscript (r: Range<Int>) -> String {
get {
let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
let endIndex = self.index(self.startIndex, offsetBy: r.upperBound)
return self[startIndex..<endIndex]
}
}
//MARK: - 判断是不是正确的银行卡号
func isCardNumber(_ cardNumber:String) {
}
//MARK: - 计算字符串的高
func height(_ width:CGFloat,fontSize:CGFloat) -> CGFloat {
let attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: fontSize)]
let option = WPOCBridging.stringDrawingOptions()
let size = CGSize(width: width, height: CGFloat(MAXFLOAT))
let rect:CGRect = self.boundingRect(with: size, options: option, attributes: attributes, context: nil)
return rect.height
}
//MARK: - 计算字符串的宽
func width(_ height:CGFloat,fontSize:CGFloat) -> CGFloat {
let attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: fontSize)]
let option = WPOCBridging.stringDrawingOptions()
let size = CGSize(width: CGFloat(MAXFLOAT), height: height)
let rect:CGRect = self.boundingRect(with: size, options: option, attributes: attributes, context: nil)
return rect.width
}
func randomText(_ length: Int, justLowerCase: Bool = false, whitespace: Bool = false) -> String {
var text = ""
for _ in 0..<length {
let count = UInt32(wp_titles.length)
let strIndex = Int(arc4random_uniform(count - 1))
let numStr = wp_titles.substring(strIndex, length: 1)
text = text + numStr
}
return text
}
/**
获取随机文本 (a-z 0-9)
- parameter length: 随机数长度
*/
public static func randomTextString(_ length : Int ) -> String {
var timeStr = String(Int64(Date().timeIntervalSince1970 ))
for _ in 0..<length {
let count = UInt32(wp_titles.length)
let strIndex = Int(arc4random_uniform(count - 1))
let numStr = wp_titles.substring(strIndex, length: 1)
timeStr = timeStr + numStr
}
return timeStr
}
//MARK: - String转时间戳
/** String转时间戳 13位
*/
func stringTotimeTamp(_ format:String) -> String {
let dfmatter = DateFormatter()
dfmatter.dateFormat=format
let date = dfmatter.date(from: self)
let dateStamp:TimeInterval = date!.timeIntervalSince1970*1000
let dateSt:Int64 = Int64(dateStamp)
return String(dateSt)
}
//MARK: - 时间戳转String
/** 时间戳转String
*/
func timeTampToString(_ format:String = "YYYY-MM-dd HH:mm:ss") -> String {
let outputFormat = DateFormatter()
var myDataSource: NSString = self as NSString
if myDataSource.length == 13 {
myDataSource = myDataSource.substring(to: 10) as NSString
}else if myDataSource.length == 15 {
myDataSource = String(myDataSource.integerValue / 1000) as NSString
}
//格式化规则
// outputFormat.dateFormat = "yyyy/MM/dd HH:mm:ss"
outputFormat.dateFormat = format
//发布时间
let pubTime = Date(timeIntervalSince1970: myDataSource.doubleValue)
return outputFormat.string(from: pubTime)
}
var length: Int {
get {
return self.characters.count
}
}
func contains(_ substring: String) -> Bool {
return range(of: substring) != nil
}
/// EZSE: Checking if String contains input with comparing options
public func contains(_ find: String, compareOption: NSString.CompareOptions) -> Bool {
return self.range(of: find, options: compareOption) != nil
}
/// EZSE: Converts String to Int
public func toInt() -> Int? {
if let num = NumberFormatter().number(from: self) {
return num.intValue
} else {
return 0
}
}
/// EZSE: Converts String to Double
public func toDouble() -> Double? {
if let num = NumberFormatter().number(from: self) {
return num.doubleValue
} else {
return nil
}
}
/// EZSE: Converts String to Float
public func toFloat() -> Float? {
if let num = NumberFormatter().number(from: self) {
return num.floatValue
} else {
return nil
}
}
//2个数字字符串相乘
public func multiplyBy(_ string:String) -> Double {
guard let num1 = NumberFormatter().number(from: self) else{ return 0 }
guard let num2 = NumberFormatter().number(from: string) else{ return 0 }
return num1.doubleValue*num2.doubleValue
}
}
extension Double {
//Double保留几位小数
func format(_ f: String) -> String {
return NSString(format: "%\(f)f" as NSString, self) as String
}
}
UIButton+Extension
extension UIButton
{
func title(_ title : String?) {
self.setTitle(title, for: .normal)
}
func textColor(_ textColor : UIColor) {
self.setTitleColor(textColor, for: .normal)
}
convenience init(image:String!,title:String,color:UIColor,fontSize:CGFloat)
{
self.init()
if image != nil {
self.setImage(UIImage(named: image), for: .normal)
}
self.setTitle(title, for: .normal)
self.setTitleColor(color, for: .normal)
self.titleLabel?.font = UIFont.systemFont(ofSize: fontSize)
}
convenience init(image:String!,selectedImage:String!,action:LSUIControlAction!)
{
self.init()
if image != nil {
self.setImage(UIImage(named: image), for: .normal)
}
if selectedImage != nil {
self.setImage(UIImage(named: selectedImage), for: .selected)
}
if action != nil {
self.addTarget(action)
}
}
convenience init(image:String!,selectedImage:String! = nil)
{
self.init()
if image != nil {
self.setImage(UIImage(named: image), for: .normal)
}
if selectedImage != nil {
self.setImage(UIImage(named: selectedImage), for: .selected)
}
}
convenience init(title:String,color:UIColor,fontSize:CGFloat)
{
self.init()
self.setTitle(title, for: .normal)
self.setTitleColor(color, for: .normal)
self.titleLabel?.font = UIFont.systemFont(ofSize: fontSize)
}
convenience init(title:String,color:UIColor,selectedColor:UIColor,fontSize:CGFloat)
{
self.init()
self.setTitle(title, for: .normal)
self.setTitleColor(color, for: .normal)
self.setTitleColor(selectedColor, for: UIControlState.selected)
self.titleLabel?.font = UIFont.systemFont(ofSize: fontSize)
}
convenience init(title:String,color:UIColor,selectedColor:UIColor,fontSize:CGFloat,action:@escaping LSUIControlAction)
{
self.init()
self.setTitle(title, for: .normal)
self.setTitleColor(color, for: .normal)
self.setTitleColor(selectedColor, for: UIControlState.selected)
self.titleLabel?.font = UIFont.systemFont(ofSize: fontSize)
self.addTarget(action)
}
}
UIDevice + EX
extension String {
static func currentDeviceScreenMeasurement() -> CGFloat {
var deviceScree: CGFloat = 3.5
if ((568 == ScreenHeight && 320 == ScreenWidth) || (1136 == ScreenHeight && 640 == ScreenWidth)) {
deviceScree = 4.0;
} else if ((667 == ScreenHeight && 375 == ScreenWidth) || (1334 == ScreenHeight && 750 == ScreenWidth)) {
deviceScree = 4.7;
} else if ((736 == ScreenHeight && 414 == ScreenWidth) || (2208 == ScreenHeight && 1242 == ScreenWidth)) {
deviceScree = 5.5;
}
return deviceScree
}
static func getVersion() ->String {
guard let versionCode = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as? String else {
return "-1"
}
return versionCode
}
static func getBuild() ->String {
guard let build = Bundle.main.infoDictionary!["CFBundleVersion"] as? String else {
return "-1"
}
return build
}
/// 获取设备唯一UUID
public static func getUUID() -> String {
let key = "KeychainWeddingerPush"
let retrievedString: String? = KeychainWrapper.standard.string(forKey: key)
if retrievedString == nil {
let uidStr = UIDevice.current.identifierForVendor!.uuidString
let saveSuccessful: Bool = KeychainWrapper.standard.set(uidStr, forKey: key)
if saveSuccessful {
var str = uidStr as NSString
str = str.replacingOccurrences(of: "-", with: "") as NSString
str = str.substring(to: 16) as NSString
return str as String
}
return ""
}else{
var str = retrievedString! as NSString
str = str.replacingOccurrences(of: "-", with: "") as NSString
str = str.substring(to: 16) as NSString
return str as String
}
}
}
UIImage + Extension
extension UIImage {
class func imageWithColor(_ color: UIColor, size: CGSize, alpha: CGFloat = 1.0) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(rect.size)
let ref = UIGraphicsGetCurrentContext()
ref?.setAlpha(alpha)
ref?.setFillColor(color.cgColor)
ref?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
class func createImageFromView(_ view: UIView) -> UIImage {
UIGraphicsBeginImageContext(view.bounds.size);
view.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image!
}
func imageClipOvalImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)
let ctx = UIGraphicsGetCurrentContext()
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
ctx?.addEllipse(in: rect)
ctx?.clip()
self.draw(in: rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
/**
* 获得指定size的图片
*
* image 原始图片
* newSize 指定的size
*
* return 调整后的图片
*/
class func resizeImage(_ image: UIImage, newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContext(newSize)
image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
/**
* 压缩上传图片到指定字节
*
* image 压缩的图片
* maxLength 压缩后最大字节大小
*
* return 压缩后图片的二进制
*/
class func compressImage(_ image: UIImage, maxLength: Int) -> Data? {
let newSize = UIImage.scaleImage(image, imageLength: 300)
let newImage = UIImage.resizeImage(image, newSize: newSize)
var compress:CGFloat = 0.9
var data = UIImageJPEGRepresentation(newImage, compress)
while data?.count > maxLength && compress > 0.01 {
compress -= 0.02
data = UIImageJPEGRepresentation(newImage, compress)
}
return data
}
///对指定图片进行拉伸
class func resizableImage(_ name: String) -> UIImage {
var normal = UIImage(named: name)!
let imageWidth = normal.size.width * 0.5
let imageHeight = normal.size.height * 0.5
normal = normal.resizableImage(withCapInsets: UIEdgeInsetsMake(imageHeight, imageWidth, imageHeight, imageWidth))
return normal
}
/**
* 通过指定图片最长边,获得等比例的图片size
*
* image 原始图片
* imageLength 图片允许的最长宽度(高度)
*
* return 获得等比例的size
*/
class func scaleImage(_ image: UIImage, imageLength: CGFloat) -> CGSize {
var newWidth:CGFloat = 0.0
var newHeight:CGFloat = 0.0
let width = image.size.width
let height = image.size.height
if (width > imageLength || height > imageLength){
if (width > height) {
newWidth = imageLength;
newHeight = newWidth * height / width;
}else if(height > width){
newHeight = imageLength;
newWidth = newHeight * width / height;
}else{
newWidth = imageLength;
newHeight = imageLength;
}
}else {
newWidth = width;
newHeight = height;
}
return CGSize(width: newWidth, height: newHeight)
}
/**
图片存储
- parameter image:
- parameter imageName:
*/
func savieImage(_ image : UIImage, imageName: String) {
let jpgData = UIImageJPEGRepresentation(image, CGFloat(1));
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! + imageName + ".jpg"
FileManager.default.createFile(atPath: path, contents: jpgData, attributes: nil)
print("图片存储地址 \(path)")
}
}
UIView+Extension
/// 对UIView的扩展
extension UIView {
//MARK:边框
func border(_ color:UIColor,width:CGFloat)
{
self.layer.borderColor = color.cgColor
self.layer.borderWidth = width
self.layer.cornerRadius = 4
}
//MARK:圆角
func cornerRadius(_ radius:CGFloat)
{
self.layer.masksToBounds = true
self.layer.cornerRadius = radius
}
//MARK: - 移除View所有的子视图
func removeAllSubViews() {
for view in self.subviews {
view.removeFromSuperview()
}
}
//MARK: - 添加虚线边框
func addDottedLineBorder() {
//虚线边框
let border = CAShapeLayer()
border.strokeColor = COLOR_lightGray.cgColor
border.fillColor = nil
border.path = UIBezierPath(rect: self.bounds).cgPath
border.frame = self.bounds
border.lineCap = "square"
border.lineWidth = 1.0
border.lineDashPattern = [4,3]
self.layer.addSublayer(border)
}
//MARK: - 添加虚线
func dottedLineView(_ lineWidth : CGFloat = 1.0,lineDashPattern : [NSNumber] = [4,3] ) {
let border = CAShapeLayer()
border.strokeColor = COLOR_lightGray.cgColor
border.fillColor = nil
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: self.width, y: 0))
border.path = path.cgPath
border.frame = self.bounds
border.lineCap = "square"
border.lineWidth = lineWidth
border.lineDashPattern = lineDashPattern
self.layer.addSublayer(border)
}
//MARK: - 初始化
convenience init(bgColor:UIColor) {
self.init()
self.backgroundColor = bgColor
}
}