该文档用于记录iOS中常用的类方法
swift原生的字符串处理方法依然不方便,当前对字符串的部分内容进行处理依然采用NSString的方法NSRange的结构里包含location和length,可以较为方便获取某个字符的当前位置let str = "abcd 1234"
let attrStr = NSMutableAttributedString(string: str)
//获取空格处的位置信息
let midIndex = (str as NSString).range(of: " ").location
let range1 = NSRange(location: 0, length: midIndex)
let range2 = NSRange(location: midIndex, length: str.count - midIndex)
//设置富文本
attrStr.setAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 28)], range: range1)
//当设置为UILabel的富文本时,未进行设置的富文本按默认格式展示
label.attributedText = attrStr
UILabel)只有水平位置上的对齐,没有文字垂直方向上的调整,故要实现只能借助富文本的方法对其位置进行移动NSAttributedString的baselineOffset方法可以使富文本的文字位置以底端为基准进行移动,可以通过文字大小大致计算并实现底端对齐或者垂直居中对齐attrStr.setAttributes([NSAttributedString.Key.baselineOffset: 5], range: range1)
将颜色的十六进制字符串转换为具体颜色样式
extension UIColor{
convenience init(valueStr:String) {
let scanner:Scanner = Scanner(string:valueStr)
var valueRGB:UInt32 = 0
if scanner.scanHexInt32(&valueRGB) == false {
self.init(red: 0,green: 0,blue: 0,alpha: 0)
}else{
self.init(
red:CGFloat((valueRGB & 0xFF0000)>>16)/255.0,
green:CGFloat((valueRGB & 0x00FF00)>>8)/255.0,
blue:CGFloat(valueRGB & 0x0000FF)/255.0,
alpha:CGFloat(1.0)
)
}
}
}
Date()方法获取的是手机里显示的时间,而非标准时间//获取当前手机设置的时间,而非标准时间
let now = Date()
let timeInterval = now.timeIntervalSince1970
print("当前的时间戳:\(timeInterval)")
let date = Date(timeIntervalSince1970: timeInterval)
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
print("时间戳对应的时间:\(formatter.string(from: date))")
let now = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
print("时间戳对应的时间:\(formatter.string(from: now))")
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute fromDate:now];
NSDate *startDate = [calendar dateFromComponents:components];
NSInteger timeStamp = [startDate timeIntervalSince1970];
NSLog(@"now:%@, date:%@, stamp:%ld", now, startDate, timeStamp);
extension Array where Element == UInt8 {
var hexString: String {
return self.compactMap { String(format: "%02x", $0).uppercased() }
.joined(separator: "")
}
}
func += <KeyType, ValueType> ( left: inout Dictionary<KeyType, ValueType>, right: Dictionary<KeyType, ValueType>) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
}
+=操作符将另一个字典载入当前字典内