String+Extenstion.swift 5.4 KB

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