<dl id="opymh"></dl>

<div id="opymh"></div>
      <div id="opymh"><tr id="opymh"></tr></div>

        <em id="opymh"><ins id="opymh"><mark id="opymh"></mark></ins></em><sup id="opymh"><menu id="opymh"></menu></sup>

        <em id="opymh"></em>

        <em id="opymh"><ol id="opymh"></ol></em>

              頻道欄目
              首頁 > 程序開發 > 移動開發 > IOS > 正文
              IOS開發中常用的代碼塊收集整理
              2018-07-30 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._%+-][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技術培訓 | 舉報中心

              版權所有: 紅黑聯盟--致力于做實用的IT技術學習網站

              极速飞艇好假
              <dl id="opymh"></dl>

              <div id="opymh"></div>
                  <div id="opymh"><tr id="opymh"></tr></div>

                    <em id="opymh"><ins id="opymh"><mark id="opymh"></mark></ins></em><sup id="opymh"><menu id="opymh"></menu></sup>

                    <em id="opymh"></em>

                    <em id="opymh"><ol id="opymh"></ol></em>

                          <dl id="opymh"></dl>

                          <div id="opymh"></div>
                              <div id="opymh"><tr id="opymh"></tr></div>

                                <em id="opymh"><ins id="opymh"><mark id="opymh"></mark></ins></em><sup id="opymh"><menu id="opymh"></menu></sup>

                                <em id="opymh"></em>

                                <em id="opymh"><ol id="opymh"></ol></em>