49 lines
2.2 KiB
Swift
49 lines
2.2 KiB
Swift
//
|
||
// String.swift
|
||
// MusicPlayer
|
||
//
|
||
// Created by Mr.Zhou on 2024/4/7.
|
||
//
|
||
|
||
import Foundation
|
||
extension String {
|
||
/// 字符串转类type
|
||
func classFromString() -> AnyClass? {
|
||
// 获swift中的命名空间名
|
||
var name = Bundle.main.object(forInfoDictionaryKey: "CFBundleExecutable") as? String
|
||
// 如果包名中有'-'横线这样的字符,在拿到包名后,还需要把包名的'-'转换成'_'下横线
|
||
name = name?.replacingOccurrences(of: "-", with: "_")
|
||
// 拼接命名空间和类名,”包名.类名“
|
||
let fullClassName = name! + "." + self
|
||
// 因为NSClassFromString()返回的AnyClass?,需要给个默认值返回!
|
||
let anyClass: AnyClass? = NSClassFromString(fullClassName)
|
||
// 类type
|
||
return anyClass
|
||
}
|
||
//MARK: - 字符串扩展
|
||
///根据宽度跟字体,计算文字的高度
|
||
func textAutoHeight(width:CGFloat, font:UIFont) ->CGFloat{
|
||
let string = self as NSString
|
||
let origin = NSStringDrawingOptions.usesLineFragmentOrigin
|
||
let lead = NSStringDrawingOptions.usesFontLeading
|
||
let ssss = NSStringDrawingOptions.usesDeviceMetrics
|
||
let rect = string.boundingRect(with:CGSize(width: width, height:0), options: [origin,lead,ssss], attributes: [NSAttributedString.Key.font:font], context:nil)
|
||
return rect.height
|
||
}
|
||
///根据高度跟字体,计算文字的宽度
|
||
func textAutoWidth(height:CGFloat, font:UIFont) ->CGFloat{
|
||
let string = self as NSString
|
||
let origin = NSStringDrawingOptions.usesLineFragmentOrigin
|
||
let lead = NSStringDrawingOptions.usesFontLeading
|
||
let rect = string.boundingRect(with:CGSize(width:0, height: height), options: [origin,lead], attributes: [NSAttributedString.Key.font:font], context:nil)
|
||
return rect.width
|
||
}
|
||
}
|
||
extension Range where Bound == String.Index {
|
||
func toNSRange(in string: String) -> NSRange {
|
||
let utf16IndexStart = string.utf16.distance(from: string.utf16.startIndex, to: lowerBound)
|
||
let utf16IndexEnd = string.utf16.distance(from: string.utf16.startIndex, to: upperBound)
|
||
return NSRange(location: utf16IndexStart, length: utf16IndexEnd - utf16IndexStart)
|
||
}
|
||
}
|