Swift 常用方法总结

Swift 常用方法总结

1、设置AttributeStringText

 //MARK: - 设置富文本
 func setAttributeStringText(strFullText:String, andFullTextFont textFont:UIFont, andFullTextColor textColor:UIColor, withChangeText changeText:String, withChangeFont changFont:UIFont, withChangeColor changeColor:UIColor) -> NSAttributedString{
    
    let attributeString = NSMutableAttributedString.init(string: strFullText)
    
    //需要改变的文本
    var range = NSString.init(string: strFullText).range(of: changeText)
    attributeString.addAttributes([
        NSFontAttributeName:changFont,
        NSForegroundColorAttributeName:changeColor,
        ], range: range)
    
    //不需要改变的文本
    let oldText = NSString.init(string: strFullText).replacingOccurrences(of: changeText, with: "")
    range = NSString.init(string: strFullText).range(of: oldText)
    attributeString.addAttributes([
        NSFontAttributeName:textFont,
        NSForegroundColorAttributeName:textColor,
        ], range: range)
    
    return attributeString
 }

 

2、是否含有Emoji表情

 //MARK: - Emoji表情检测
 //是否含有Emoji 表情(true 含有)
 func stringContainsEmoji(string:String)->Bool{
    var returnValue = false;
    let Str = NSString(format: "%@", string);
    
    Str.enumerateSubstrings(in: NSMakeRange(0, Str.length), options: NSString.EnumerationOptions.byComposedCharacterSequences) { (substring, substringRange, enclosingRange, stop) in
        
        let subStr = NSString(format: "%@", substring!);
        let hs = subStr.character(at: 0);
        // surrogate pair
        if (0xd800 <= hs && hs <= 0xdbff) {
            if (subStr.length > 1) {
                let ls = subStr.character(at: 1);
                let uc = Int(((hs - 0xd800) * 0x400) + (ls - 0xdc00)) + 0x10000;
                if (0x1d000 <= uc && uc <= 0x1f77f){
                    returnValue = true;
                }
            }
        }
        else if (subStr.length > 1) {
            let ls = subStr.character(at: 1);
            if (ls == 0x20e3){
                returnValue = true;
            }
        }
        else {
            // non surrogate
            if (0x2100 <= hs && hs <= 0x27ff){
                returnValue = true;
            }
            else if (0x2B05 <= hs && hs <= 0x2b07){
                returnValue = true;
            }
            else if (0x2934 <= hs && hs <= 0x2935){
                returnValue = true;
            }
            else if (0x3297 <= hs && hs <= 0x3299){
                returnValue = true;
            }
            else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50){
                returnValue = true;
            }
        }
    };  
    
    return returnValue;
 }

 

3、获取文本的宽度

 //MARK: - 获取文本的宽度
 func getWidthForString(strTitle:String,txtFont:UIFont) -> CGFloat {
    var fw = CGFloat.init(0)
    
    let size = NSString.init(string: strTitle).size(attributes: [
        NSFontAttributeName:txtFont
        ])
    fw = size.width
    
    return fw
 }

 

4、字典转换为Json String

   /**
    * 字典转换为JSONString
    * @parameter dictionary: 字典参数
    * @returns: JSONString
    */
    func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            print("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData!
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String

    }

 

5、UISearchBar样式属性修改

//MARK: - UISearchBar相关设置
//清除查询框背景
func clearnSearchBarBg(searchView:UISearchBar){

    for item:UIView in (searchView.subviews) {
        for subview:UIView in item.subviews {
            if subview.isKind(of: UITextField.classForCoder()) {

                //将搜索文本框的背景去掉
                for obj in subview.subviews {
                    obj.removeFromSuperview()
                }
            }
        }
    }
}

//设置取消按钮为中文
func setSearchBarCancle(searchView:UISearchBar){

    for item:UIView in (searchView.subviews) {
        for subview:UIView in item.subviews {

            //更改取消按钮
            if subview.isKind(of:UIButton.classForCoder()) {
                let btnCancle:UIButton = subview as! UIButton

                //修改文本
                btnCancle.setTitle("取消", for: .normal)

                //修改背景
                btnCancle.backgroundColor = UIColor.clear
            }
        }
    }
}

//设置提示文本字体大小
func setSearchBarFont(searchView:UISearchBar,font:UIFont){

    for item:UIView in (searchView.subviews) {
        for subview:UIView in item.subviews {
            if subview.isKind(of: UITextField.classForCoder()) {
              (subview as? UITextField)?.font = font
            }
        }
    }
}

6、文件上传

/**!
 * 文件或图片上传
 * @para strUrl String 上传地址
 * @para uploadformDataBack 上传参数设置
 * @para successBack  成功回调
 * @para failureBack  失败回调
 */
func postImageUploadToServer(strUrl:String,
                             uploadformDataBack:@escaping(_ fData:AFMultipartFormData)->(),
                             AndSuccessBack successBack:@escaping(_ responseData:Any?)->(),
                             AndFailureBack failureBack:@escaping(_ responseString:String?)->(),
                             WithisLoading isLoading:Bool = true){

    print("上传地址:\(strUrl)")

    if isLoading == true {
       DispatchQueue.main.async {
           SVProgressHUD.show(withStatus: " 上传中... ")
       }
    }

    let sessionManager = AFHTTPSessionManager.init()

    sessionManager.requestSerializer.timeoutInterval = K_APP_REQUEST_TIME_OUT
    sessionManager.requestSerializer.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
    
    sessionManager.responseSerializer = AFJSONResponseSerializer()
    sessionManager.responseSerializer.acceptableContentTypes = K_APP_ACCEPTABLE_CONTENTTYPES
    
    sessionManager.post(strUrl, parameters: nil, constructingBodyWith: { (formData:AFMultipartFormData) in

        //指定参数
        uploadformDataBack(formData)

    }, progress: nil, success: { (sessionDataTask:URLSessionDataTask?, responseData:Any?) in

         DispatchQueue.main.async {
            SVProgressHUD.dismiss()
         }

        if let jsonObj:[String:Any] = responseData as? [String:Any] {
             //请求成功
             if K_API_IS_OK(rs: jsonObj[K_API_RESULT_CODE]) {

                 DispatchQueue.main.async {
                        SVProgressHUD.dismiss()
                 }
                 successBack(jsonObj[K_API_RESULT_DATA])
             }
             else{
                 var _str:String? = jsonObj[K_API_RESULT_MESSAGE] as? String
                 if _str == nil {
                     _str = "文件上传失败"
                 }
                 failureBack(_str)
             }
        }
        else{
            failureBack("文件上传失败")
        }
    }, failure: { (sessionDataTask:URLSessionDataTask?, error:Error) in
        DispatchQueue.main.async {
           SVProgressHUD.dismiss()
        }

        print(error.localizedDescription)
        failureBack(error.localizedDescription)
    })?.resume()
}

K_APP_ACCEPTABLE_CONTENTTYPES:

/** 网络请求的支持类型 */
let K_APP_ACCEPTABLE_CONTENTTYPES:Set<String> = ["application/json", "text/json", "text/javascript","text/plain","text/html"]

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追夢秋陽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值