• 我相信“交警雨中护送高考生”是真,“交警雨中护送高考生”反被该高考生家长投诉是假。 2019-04-16
  • 14名消防员日巡逻28公里 洗冷水澡 2019-04-10
  • 靶壕有了“蓝军”,百发百中的“神枪手”练起来 2019-04-10
  • 不是秀强大了,别人就会来做朋友,这逻辑不对 2019-04-01
  • 候选企业:中国石油呼和浩特石化公司 2019-03-26
  • 航天员沙漠野外生存训练完美收官!为第一天团打call 2019-03-25
  • 请问,建立市场经济后,原计划经济哪里去?改革后,我们还在实行计划经济,为何没有提及? 2019-03-25
  • 构建年轻干部梯次培养链 2019-03-19
  • 孙实的专栏作者中国国家地理网 2019-03-15
  • 湖南师范大学举行研究阐释党的十九大精神国家社科基金重大专项学术研讨会 2019-03-15
  • [雷人]蠢货!土地处于不同的城市和地段,关联的资源不一样,价值也不一样。不然给咱俩同样面积的土地,咱的在北上广深,你的在边远山区,你干么? 2019-03-08
  • 国际社会持续热议上合青岛峰会:上合组织发展进入新阶段 彰显中国领导力 2019-03-08
  • 珍惜野生动物频现甘孜境内 生态环境质量不断提升 2019-03-06
  • "新经济形势下金融创新的变革与机遇"论坛 2019-03-06
  • 频道栏目
    神奇公式秒杀全国11选5 > 程序开发 > 移动开发 > IOS > 正文
    IOS开发中常用的代码块收集整理
    2018-07-30 15:40:20         来源:die_word的博客  
    收藏   我要投稿

    神奇公式秒杀全国11选5 www.2zfa.com 收集常用的代码块是加快开发的有效途径,收集的操作步骤这里不在赘述,仅仅贡献上一些常用的功能性代码

    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._%+-][email protected][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技术培训 | 神奇公式秒杀全国11选5

    版权所有: 神奇公式秒杀全国11选5--致力于做实用的IT技术学习网站

  • 我相信“交警雨中护送高考生”是真,“交警雨中护送高考生”反被该高考生家长投诉是假。 2019-04-16
  • 14名消防员日巡逻28公里 洗冷水澡 2019-04-10
  • 靶壕有了“蓝军”,百发百中的“神枪手”练起来 2019-04-10
  • 不是秀强大了,别人就会来做朋友,这逻辑不对 2019-04-01
  • 候选企业:中国石油呼和浩特石化公司 2019-03-26
  • 航天员沙漠野外生存训练完美收官!为第一天团打call 2019-03-25
  • 请问,建立市场经济后,原计划经济哪里去?改革后,我们还在实行计划经济,为何没有提及? 2019-03-25
  • 构建年轻干部梯次培养链 2019-03-19
  • 孙实的专栏作者中国国家地理网 2019-03-15
  • 湖南师范大学举行研究阐释党的十九大精神国家社科基金重大专项学术研讨会 2019-03-15
  • [雷人]蠢货!土地处于不同的城市和地段,关联的资源不一样,价值也不一样。不然给咱俩同样面积的土地,咱的在北上广深,你的在边远山区,你干么? 2019-03-08
  • 国际社会持续热议上合青岛峰会:上合组织发展进入新阶段 彰显中国领导力 2019-03-08
  • 珍惜野生动物频现甘孜境内 生态环境质量不断提升 2019-03-06
  • "新经济形势下金融创新的变革与机遇"论坛 2019-03-06