String+Extenstion.swift 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. //
  2. // String+Extenstion.swift
  3. // o2app
  4. //
  5. // Created by 刘振兴 on 2017/8/18.
  6. // Copyright © 2017年 zone. All rights reserved.
  7. //
  8. import Foundation
  9. import UIKit
  10. extension String {
  11. /// 获取扩展名 比如 png gif 等
  12. public var pathExtension: String {
  13. guard let url = URL(string: self) else { return "" }
  14. return url.pathExtension.isEmpty ? "" : url.pathExtension
  15. }
  16. /// 获取文件名称
  17. public var pathFileName: String {
  18. guard let url = URL(string: self) else {
  19. return ""
  20. }
  21. return url.lastPathComponent
  22. }
  23. /// EZSE: Checks if string is empty or consists only of whitespace and newline characters
  24. public var isBlank: Bool {
  25. let trimmed = trimmingCharacters(in: .whitespacesAndNewlines)
  26. return trimmed.isEmpty
  27. }
  28. /// EZSE: split string using a spearator string, returns an array of string
  29. public func split(_ separator: String) -> [String] {
  30. return self.components(separatedBy: separator).filter {
  31. !$0.trim().isEmpty
  32. }
  33. }
  34. /// EZSE: split string with delimiters, returns an array of string
  35. public func split(_ characters: CharacterSet) -> [String] {
  36. return self.components(separatedBy: characters).filter {
  37. !$0.trim().isEmpty
  38. }
  39. }
  40. public func trim(trimNewline: Bool = false) ->String {
  41. if trimNewline {
  42. return self.trimmingCharacters(in: .whitespacesAndNewlines)
  43. }
  44. return self.trimmingCharacters(in: .whitespaces)
  45. }
  46. /// 字符串时间转 Date
  47. ///
  48. /// - Parameter formatter: 字符串时间的格式 yyyy-MM-dd/YYYY-MM-dd/HH:mm:ss/yyyy-MM-dd HH:mm:ss
  49. /// - Returns: Date
  50. func toDate(formatter: String) -> Date {
  51. let dateFormatter = DateFormatter()
  52. dateFormatter.locale = Locale.current
  53. dateFormatter.dateFormat = formatter
  54. let date = dateFormatter.date(from: self)
  55. return date!
  56. }
  57. var length: Int {
  58. return self.count
  59. }
  60. func subString(from: Int, to: Int? = nil) -> String {
  61. if from >= self.length {
  62. return self
  63. }
  64. let startIndex = self.index(self.startIndex, offsetBy: from)
  65. if to == nil {
  66. return String(self[startIndex..<self.endIndex])
  67. }else {
  68. if from >= to! {
  69. return String(self[startIndex..<self.endIndex])
  70. }else {
  71. let endIndex = index(self.startIndex, offsetBy: to!)
  72. return String(self[startIndex..<endIndex])
  73. }
  74. }
  75. }
  76. /// 计算文本的高度
  77. func textHeight(fontSize: CGFloat, width: CGFloat) -> CGFloat {
  78. return self.boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [.font: UIFont.systemFont(ofSize: fontSize)], context: nil).size.height
  79. }
  80. // MARK: - URL允许的字符
  81. var urlEscaped: String {
  82. return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
  83. }
  84. var urlEncoded: String {
  85. return self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
  86. }
  87. // MARK:- 获取字符串的CGSize
  88. func getSize(with fontSize: CGFloat) -> CGSize {
  89. let str = self as NSString
  90. let size = CGSize(width: UIScreen.main.bounds.width, height: CGFloat(MAXFLOAT))
  91. return str.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontSize)], context: nil).size
  92. }
  93. // MARK: - 根据固定宽度获取字符串在label中的size
  94. func getSizeWithMaxWidth(fontSize:CGFloat, maxWidth: CGFloat) -> CGSize {
  95. let size = CGSize(width: maxWidth, height: CGFloat(MAXFLOAT))
  96. return self.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontSize)], context: nil).size
  97. }
  98. // MARK:- 获取文本图片
  99. func getTextImage(_ size:CGSize,textColor tColor:UIColor,backColor bColor:UIColor,textFont tFont:UIFont) -> UIImage? {
  100. let label = UILabel(frame: CGRect(origin:CGPoint(x:0,y:0), size: size))
  101. label.textAlignment = .center
  102. label.textColor = tColor
  103. label.font = tFont
  104. label.text = self
  105. label.backgroundColor = bColor
  106. UIGraphicsBeginImageContextWithOptions(label.frame.size, true, 0)
  107. guard let context = UIGraphicsGetCurrentContext() else { return nil }
  108. label.layer.render(in: context)
  109. let image = UIGraphicsGetImageFromCurrentImageContext()
  110. UIGraphicsEndImageContext()
  111. return image
  112. }
  113. subscript(r: Range<Int>) -> String {
  114. get {
  115. let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
  116. let endIndex = self.index(self.startIndex, offsetBy: r.upperBound)
  117. return String(self[startIndex..<endIndex])
  118. }
  119. }
  120. subscript(r: ClosedRange<Int>) -> String {
  121. get {
  122. let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
  123. let endIndex = self.index(self.startIndex, offsetBy: r.upperBound)
  124. return String(self[startIndex...endIndex])
  125. }
  126. }
  127. static func randomString(length:Int) -> String {
  128. let charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  129. var c = charSet.map { String($0) }
  130. var s:String = ""
  131. for _ in (1...length) {
  132. s.append(c[Int(arc4random()) % c.count])
  133. }
  134. return s
  135. }
  136. // MARK:- 获取帐号中的中文名称
  137. func getChinaName() -> String{
  138. let userName = self
  139. var strTemp = ""
  140. if !userName.isBlank{
  141. let userNameSplit = userName.split("@");
  142. if strTemp == "" {
  143. strTemp = userNameSplit[0]
  144. }else{
  145. strTemp = strTemp + "," + userNameSplit[0]
  146. }
  147. print(strTemp)
  148. }
  149. return strTemp
  150. }
  151. }