String+Extenstion.swift 5.7 KB

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