<dfn id='w2X9Anwm'></dfn>

        <noscript id='w2X9Anwm'></noscript>

      1. 频道栏目
        首页 > 程序开发 > 移动开发 > IOS > 正文
        IOS开发中常用的代码块收集整理
        2019-02-20 15:40:20         来源:die_word的博客  
        收藏   我要投稿

        收集常用的代码块是加快开发的有效途径,收集的操作步骤这里不在赘述,仅仅贡献上一些常用的功能性代码

        1、与高度和宽度有关的

         /*获取导航栏高度*/
         public func getNavigationBarHeight() -> CGFloat {
          let navRect:CGRect! = self.navigationController?.navigationBar.frame
          return navRect.size.height
         }
         /*获取标签栏高度*/
         public func getTabBarHeight() -> CGFloat {
          let tabBarRect:CGRect! = self.tabBarController?.tabBar.frame
          return tabBarRect.size.height
         }
         /*获取状态栏高度*/
         public func getStatusBarHeight() -> CGFloat {
          let rectStatus:CGRect = UIApplication.shared.statusBarFrame
          return rectStatus.size.height
         }
        
         /*根据提供的字体大小,宽度获取字文字的高度*/
         func getTextHeigh(textStr:String,font:UIFont,width:CGFloat) -> CGFloat {
          let normalText: NSString = textStr as NSString
          let size = CGSize(width: width, height: 10000)
          let dic:NSDictionary = NSDictionary(object: font, forKey: NSAttributedStringKey.font as NSCopying)
          let stringSize = normalText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedStringKey : Any], context:nil).size
          return stringSize.height
         }
         
         /*提供文字大小,控件高度,获取到文字的宽度*/
         func getTexWidth(textStr:String,font:UIFont,height:CGFloat) -> CGFloat {
          let normalText: NSString = textStr as NSString
          let size = CGSize(width: 10000, height: height)
          let dic:NSDictionary = NSDictionary(object: font, forKey: NSAttributedStringKey.font as NSCopying)
          let stringSize = normalText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedStringKey : Any], context:nil).size
          return stringSize.width + 40
         }
        
         UIScreen.main.bounds.size.width // 屏幕宽度
         UIScreen.main.bounds.size.height // 屏幕高度
        
        
         /*UIFont的适配(创建UIFont的扩展)*/
        + (void)load {
         Method newMethod = class_getClassMethod([self class], @selector(adjustFont:));
         Method method = class_getClassMethod([self class], @selector(systemFontOfSize:));
         method_exchangeImplementations(newMethod, method);
        }
        
        + (UIFont *)adjustFont:(CGFloat)fontSize {
         UIFont *newFont = nil;
         //BaseWidth 为设计图的尺寸
         newFont = [UIFont adjustFont:fontSize * [UIScreen mainScreen].bounds.size.width / BaseWidth];
         return newFont;
        }
        
         

        2、处理类相关

        
        /*十六进制颜色*/
        func RGBColorFromHex(rgbValue: Int) -> (UIColor) {
         return UIColor(red: ((CGFloat)((rgbValue & 0xFF0000) >> 16)) / 255.0,
         green: ((CGFloat)((rgbValue & 0xFF00) >> 8)) / 255.0,
         blue: ((CGFloat)(rgbValue & 0xFF)) / 255.0,
         alpha: 1.0)
        }
        
        /*时间戳转化成自定义时间格式*/
        func getTimeWithTimeInterval(timeInterval:TimeInterval, dataFormart:String) -> String {
          let date:Date = Date(timeIntervalSince1970: timeInterval / 1000)
          let formatter:DateFormatter = DateFormatter.init()
          formatter.dateFormat = dataFormart
          let timeStr:String = formatter.string(from: date)
          return timeStr
         }
        
        /*字符串MD5加密*/
        - (NSString *)md5String:(NSString *)str
        {
         if (!str) return nil;
         const char *cStr = str.UTF8String;
         unsigned char result[CC_MD5_DIGEST_LENGTH];
         CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
         NSMutableString *md5Str = [NSMutableString string];
         for (int i = 0; i < CC_MD5_DIGEST_LENGTH; ++i) {
          [md5Str appendFormat:@"%02x", result[i]];
         }
         return md5Str;
        }
        
        /*微信支付签名*/
        -(NSString *)createMD5SingForPayWithAppID:(NSString *)appid_key partnerid:(NSString *)partnerid_key prepayid:(NSString *)prepayid_key package:(NSString *)package_key noncestr:(NSString *)noncestr_key timestamp:(UInt32)timestamp_key{
         NSMutableDictionary *signParams = [NSMutableDictionary dictionary];
         [signParams setObject:appid_key forKey:@"appid"];//微信appid 例如wxfb132134e5342
         [signParams setObject:noncestr_key forKey:@"noncestr"];//随机字符串
         [signParams setObject:package_key forKey:@"package"];//扩展字段  参数为 Sign=WXPay
         [signParams setObject:partnerid_key forKey:@"partnerid"];//商户账号
         [signParams setObject:prepayid_key forKey:@"prepayid"];//此处为统一下单接口返回的预支付订单号
         [signParams setObject:[NSString stringWithFormat:@"%u",timestamp_key] forKey:@"timestamp"];//时间戳
         
         NSMutableString *contentString  =[NSMutableString string];
         NSArray *keys = [signParams allKeys];
         NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
          return [obj1 compare:obj2 options:NSNumericSearch];
         }];
         for (NSString *categoryId in sortedArray) {
          if (![[signParams objectForKey:categoryId] isEqualToString:@""]
        && ![[signParams objectForKey:categoryId] isEqualToString:@"sign"]
        && ![[signParams objectForKey:categoryId] isEqualToString:@"key"]
        )
          {
        [contentString appendFormat:@"%@=%@&", categoryId, [signParams objectForKey:categoryId]];
          }
         }
         [contentString appendFormat:@"key=%@", @"utNO9LVL7LgMhfloAl8yO6ORrKIo2iky"];
         NSString *result = [self md5String:contentString];
         return result;
        }
        
        /*去除字符串的空格和换行符*/
        + (NSString *) handleNewLineAndWhitSpaceForString:(NSString *)str;{
         str = [str stringByReplacingOccurrencesOfString:@"\r" withString:@""];
         str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
         str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
         return str;
        }
        
        /*数组去除重复数据*/
        public extension Array {
         func filterDuplicates(_ filter: (Element) -> E) -> [Element] {
          var result = [Element]()
          for value in self {
        let key = filter(value)
        if !result.map({filter($0)}).contains(key) {
         result.append(value)
        }
          }
          return result
         }
        }
        
        /*图片二维码识别(使用ZXing)*/
        + (void)recognizeImage:(UIImage*)image block:(void(^)(ZXBarcodeFormat barcodeFormat,NSString *str))block {
         ZXCGImageLuminanceSource *source = [[ZXCGImageLuminanceSource alloc] initWithCGImage:image.CGImage];
         ZXHybridBinarizer *binarizer = [[ZXHybridBinarizer alloc] initWithSource: source];
         ZXBinaryBitmap *bitmap = [[ZXBinaryBitmap alloc] initWithBinarizer:binarizer];
         NSError *error;
         id reader;
         if (NSClassFromString(@"ZXMultiFormatReader")) {
          reader = [NSClassFromString(@"ZXMultiFormatReader") performSelector:@selector(reader)];
         }
         ZXDecodeHints *_hints = [ZXDecodeHints hints];
         ZXResult *result = [reader decode:bitmap hints:_hints error:&error];
         if (result == nil) {
          block(kBarcodeFormatQRCode,nil);
          return;
         }
         block(result.barcodeFormat,result.text);
        }
        
        /*swift执行一次的Dispatch_once函数*/
        public extension DispatchQueue {
         private static var _onceTracker = [String]()
         public class func once(key: String, block:()->Void) {
          objc_sync_enter(self)
          defer { objc_sync_exit(self) }
          
          if _onceTracker.contains(key) {
        return
          }
          _onceTracker.append(key)
          block()
         }
        }
        
        /*扩大按钮响应区域(创建UIButton扩展)*/
        static char topNameKey;
        static char rightNameKey;
        static char bottomNameKey;
        static char leftNameKey;
        - (void)setEnlargeEdgeWithTop:(CGFloat) top right:(CGFloat) right bottom:(CGFloat) bottom left:(CGFloat) left {
         objc_setAssociatedObject(self, &topNameKey, [NSNumber numberWithFloat:top], OBJC_ASSOCIATION_COPY_NONATOMIC);
         objc_setAssociatedObject(self, &rightNameKey, [NSNumber numberWithFloat:right], OBJC_ASSOCIATION_COPY_NONATOMIC);
         objc_setAssociatedObject(self, &bottomNameKey, [NSNumber numberWithFloat:bottom], OBJC_ASSOCIATION_COPY_NONATOMIC);
         objc_setAssociatedObject(self, &leftNameKey, [NSNumber numberWithFloat:left], OBJC_ASSOCIATION_COPY_NONATOMIC);
        }
        
        - (void)setEnlargeEdge:(CGFloat) size {
         objc_setAssociatedObject(self, &topNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);
         objc_setAssociatedObject(self, &rightNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);
         objc_setAssociatedObject(self, &bottomNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);
         objc_setAssociatedObject(self, &leftNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);
        
        }
        - (CGRect) enlargedRect
        {
         NSNumber* topEdge = objc_getAssociatedObject(self, &topNameKey);
         NSNumber* rightEdge = objc_getAssociatedObject(self, &rightNameKey);
         NSNumber* bottomEdge = objc_getAssociatedObject(self, &bottomNameKey);
         NSNumber* leftEdge = objc_getAssociatedObject(self, &leftNameKey);
         if (topEdge && rightEdge && bottomEdge && leftEdge)
         {
          return CGRectMake(self.bounds.origin.x - leftEdge.floatValue,
          self.bounds.origin.y - topEdge.floatValue,
          self.bounds.size.width + leftEdge.floatValue + rightEdge.floatValue,
          self.bounds.size.height + topEdge.floatValue + bottomEdge.floatValue);
         }
         else
         {
          return self.bounds;
         }
        }
        
        - (UIView*) hitTest:(CGPoint) point withEvent:(UIEvent*) event
        {
         CGRect rect = [self enlargedRect];
         if (CGRectEqualToRect(rect, self.bounds))
         {
          return [super hitTest:point withEvent:event];
         }
         return CGRectContainsPoint(rect, point) ? self : nil;
        }
        
        /*获取唯一设备号*/
        
        +(NSString *) getDeviceToken {
         NSError *error;
         NSString *deviceNumber;
         deviceNumber = [SSKeychain passwordForService:@"laihudong.app" account:@"deviceToken" error:&error];
         if(error){
          NSLog(@"出现错误");
         }
         if (deviceNumber == nil ||[deviceNumber isEqualToString:@""]) {
          CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
          CFStringRef stringRef = CFUUIDCreateString(kCFAllocatorDefault, uuidRef);
          [SSKeychain setPassword:[NSString stringWithFormat:@"%@", stringRef] forService:@"laihudong.app" account:@"deviceToken"];
          deviceNumber = [NSString stringWithFormat:@"%@",stringRef];
         }
         return deviceNumber;
        }
        
        
        
        

        3、验证类相关

        
         /*验证手机号*/
         class func validatePhonoNum(phoneNumber:String) -> Bool {
          let MOBIL = "^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
          let CM = "^1(34[0-8]|(3[5-9]|5[017-9]|8[2378])\\d)\\d{7}$";
          let CU = "^1(3[0-2]|5[256]|8[56])\\d{8}$";
          let CT = "^1((33|53|8[019])[0-9]|349)\\d{7}$";
          let regextestmobile = NSPredicate(format: "SELF MATCHES %@", MOBIL)
          let regextestcm = NSPredicate(format: "SELF MATCHES %@", CM)
          let regextestcu = NSPredicate(format: "SELF MATCHES %@", CU)
          let regextestct = NSPredicate(format: "SELF MATCHES %@", CT)
          if regextestmobile.evaluate(with: phoneNumber)||regextestcm.evaluate(with: phoneNumber)||regextestcu.evaluate(with: phoneNumber)||regextestct.evaluate(with: phoneNumber) {
        return true
          }
          return false
         }
        
         
          /*验证身份证号*/
         class func validateIdCard(idCardNumber:String) -> Bool {
          let pattern = "(^[0-9]{15}$)|([0-9]{17}([0-9]|X)$)";
          let pred = NSPredicate(format: "SELF MATCHES %@", pattern)
          let isMatch:Bool = pred.evaluate(with: idCardNumber)
          return isMatch;
         }
        
         
         /*验证邮箱*/
         -(BOOL)isValidateEmail:(NSString *)email
         {
          NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
          NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELFMATCHES%@",emailRegex];
          return [emailTest evaluateWithObject:email];
         }
        
        
        
         /*判断事时间后*/
         class func validateTimeInterval(timeInterval:TimeInterval) -> Bool {
          var isBefore:Bool!
          let orderDate:Date = Date.init(timeIntervalSince1970: timeInterval / 1000)
          let currentDate:Date = Date.init(timeIntervalSinceNow: 0)
          /*时间判断*/
          if orderDate.compare(currentDate) == .orderedAscending {
        isBefore = false
          }
          
          if orderDate.compare(currentDate) == .orderedSame {
        isBefore = false
          }
          
          if orderDate.compare(currentDate) == .orderedDescending {
        isBefore = true
          }
          return isBefore
         }
        
        
         /*判断当前周几*/
         class func getWeekDay() -> Int {
          let dateFormatter:DateFormatter = DateFormatter.init()
          dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
          let date:Date = Date.init(timeIntervalSinceNow: 0)
          let interval = Int(date.timeIntervalSince1970)
          let days = Int(interval/86400)
          let weekday = ((days + 4)%7+7)%7
          return weekday == 0 ? 7 : weekday
         }
        点击复制链接 与好友分享!回本站首页
        上一篇:IOS开发之各种收起键盘的方法
        下一篇:最后一页
        相关文章
        图文推荐
        点击排行

        关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

        版权所有: 第一门户--致力于做实用的IT技术学习网站