类方法

发表于 - 4 分钟   |   --

该文档用于记录iOS中常用的类方法

1.[String]字符串方法

1.1 获取某字符的位置及其富文本设置

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

1.2 字符串富文本文字上下方向上的位移

attrStr.setAttributes([NSAttributedString.Key.baselineOffset: 5], range: range1)


2.UIColor

2.1 颜色十六进制转换

将颜色的十六进制字符串转换为具体颜色样式

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)
            )
        }
    }
}


3.时间及时间戳处理

3.1 获取时间戳

//获取当前手机设置的时间,而非标准时间
let now = Date()
let timeInterval = now.timeIntervalSince1970
print("当前的时间戳:\(timeInterval)")

3.2 将时间戳转换为具体时间

let date = Date(timeIntervalSince1970: timeInterval)
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
print("时间戳对应的时间:\(formatter.string(from: date))")

3.3 将Date直接转换为具体时间

let now = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
print("时间戳对应的时间:\(formatter.string(from: now))")

3.4设置当天整点时间

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);


4.Data

4.1 data转换为十六进制字符串

extension Array where Element == UInt8 {
    var hexString: String {
        return self.compactMap { String(format: "%02x", $0).uppercased() }
            .joined(separator: "")
    }
}


5.Dictionary

5.1 重载操作符实现字典添加字典

func += <KeyType, ValueType> ( left: inout Dictionary<KeyType, ValueType>, right: Dictionary<KeyType, ValueType>) {
    for (k, v) in right {
        left.updateValue(v, forKey: k)
    }
}


Michael Lynx

Michael Lynx

三反昼夜

rss facebook twitter github gitlab youtube mail spotify lastfm instagram linkedin pinterest medium vimeo stackoverflow reddit quora quora