美文网首页
String个人总结

String个人总结

作者: Look2021 | 来源:发表于2019-07-12 16:17 被阅读0次

    一、基础

    1.字符串替换
    let value2 = value.replacingOccurrences(of: ";", with: "")
    

    二、String与其他类型的相互转换

    \color{red}{String,Array}

    let str = "I am FlyElephant"
    let array = str.components(separatedBy:" ")
    
    let data = [1, 2, 3, 4, 5]
    let dataStr = data.map(String.init)
    let result = dataStr.joined(separator: ",")
    

    \color{red}{URL,String}

    let string = url.absoluteString
    let url = URL(string: urlSting)
    

    \color{red}{Double,String}

    // Double转String,7位小数
    let strVar = String.init(format: "%\(8)f° E   %\(8)f° N", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude)
    
    

    \color{red}{String,Data,Byte}

    let data = "你好".data(using: String.defaultCStringEncoding)
    let bytes = [UInt8](data)
    
    let data = Data(bytes: bytes, count: bytes.count)
    let typeString = data.string(encoding: .utf8) ?? ""
    

    \color{red}{String,JSON}

    if let dataFromString = result?.data(using: .utf8, allowLossyConversion: false) {
        let json = try? JSON(data: dataFromString)
        ddPrint(json)
        
        guard let jsons = json else { return }
        
        let data = try? jsons.rawData()
        guard let dataTemp = data else {
            return
        }
        let decoder = JSONDecoder()
        do {
            let obj = try decoder.decode(LastResult.self, from: dataTemp)
            self.logisticsModel = obj
            self.table.reloadData()
        } catch {
            ddPrint("数据转化错误\(error)")
        }
        
    }
    

    三、计算文字宽度

    // 动态计算Label宽度

       func getLabelWidth(str: String, font: UIFont, height: CGFloat)-> CGFloat {
            let statusLabelText: NSString = str as NSString
            let size = CGSize(width: CGFloat(MAXFLOAT), height: height)
            let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : font], context: nil).size
            return strSize.width    
        }
    

    相关文章

      网友评论

          本文标题:String个人总结

          本文链接:https://www.haomeiwen.com/subject/xvkykctx.html