您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 常用方法整理:字串計算、正則驗證、繪圖與座標轉換

編輯:iOS 開發綜合

這篇把日常開發中反覆要查的零碎方法整理在一起,方便隨時翻閱。

1. 依字級計算字串的寬高

CGSize nameSize = [name sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14], NSFontAttributeName, nil]];

2. 用生日推算年齡

輸入格式為 YYYYMMDD,輸出「X歲X個月X天」。關鍵是用 NSCalendar 的 dateComponents 直接取出年月日差值,避免自己處理閏年與月長。

- (NSString *)ageStringByBirthday:(NSString *)birthday {
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    [inputFormatter setDateFormat:@"yyyyMMdd"];
    NSDate *inputDate = [inputFormatter dateFromString:birthday];

    NSDate *today = [NSDate date];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *dayComponents = [gregorian components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay
                                                   fromDate:inputDate
                                                     toDate:today
                                                    options:0];
    long year  = [dayComponents year];
    long month = [dayComponents month];
    long day   = [dayComponents day];

    return [NSString stringWithFormat:@"%li歲%li個月%li天", year, month, day];
}

3. 讓右側導航按鈕靠攏邊距

做法是在按鈕與系統按鈕之間塞一個寬度為負值的 fixed space item,把前者往右推。

UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
rightBtn.titleLabel.font = [UIFont systemFontOfSize:11];
[rightBtn setTitleColor:[UIColor colorWithRed:255.0/255 green:93.0/255 blue:93.0/255 alpha:1]
               forState:UIControlStateNormal];
rightBtn.frame = CGRectMake(self.view.bounds.size.width - 70, 20, 60, 44);
[rightBtn addTarget:self action:@selector(attentionBtnClick:) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *rightBtnItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];

UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                           target:nil
                                                                           action:nil];
spaceItem.width = -12;

self.navigationItem.rightBarButtonItems = @[spaceItem, rightBtnItem];

4. 讓 tableView 啟動後定位到某一列

NSIndexPath *idxPath = [NSIndexPath indexPathForRow:5 inSection:0];
[self.tableView scrollToRowAtIndexPath:idxPath
                      atScrollPosition:UITableViewScrollPositionMiddle
                              animated:NO];

5. 已知寬度與字級,計算字串高度

高度給 MAXFLOAT、寬度受限,讓系統自行換行後回報實際尺寸。

- (CGSize)getHeightText:(NSString *)text {
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:14]};
    CGSize size = [text boundingRectWithSize:CGSizeMake(kWindowW - COMMON_CARD_MARGIN * 2 - 105, MAXFLOAT)
                                     options:NSStringDrawingTruncatesLastVisibleLine
                                           | NSStringDrawingUsesLineFragmentOrigin
                                           | NSStringDrawingUsesFontLeading
                                  attributes:attribute
                                     context:nil].size;
    return size;
}

6. 檢核是否為手機號碼

用 NSPredicate 做正則比對,分別針對整體手機號碼與三大電信業者的號段。

- (BOOL)isMobileNumber:(NSString *)mobileNum {
    // 移動:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
    // 聯通:130,131,132,152,155,156,185,186
    // 電信:133,1349,153,180,189
    NSString *MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    NSString *CM     = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";  // 中國移動
    NSString *CU     = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";                 // 中國聯通
    NSString *CT     = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";              // 中國電信
    // 大陸地區固話及小靈通
    // NSString *PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";

    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm     = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu     = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct     = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];

    if ([regextestmobile evaluateWithObject:mobileNum] == YES
        || [regextestcm evaluateWithObject:mobileNum] == YES
        || [regextestct evaluateWithObject:mobileNum] == YES
        || [regextestcu evaluateWithObject:mobileNum] == YES) {
        return YES;
    }
    return NO;
}

提醒:號段規則會隨時間變動,這類正則最好集中管理並定期更新,別散落在各個專案檔案裡。

7. 畫一條虛線

用 CAShapeLayer 的 lineDashPattern 設定虛線的「實線長度 / 間距」。

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self drawRect:frame];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    UIView *lineView = [[UIView alloc] init];
    lineView.frame = CGRectMake(12, rect.size.height - 1, rect.size.width - 12 * 2, 1);
    [DashedLineView drawDashLine:lineView lineLength:4 lineSpacing:3 lineColor:kRTColorWithHEX(0xd0d0d0, 1.0)];
    [self addSubview:lineView];
}

/**
 lineView   : 要畫成虛線的 view
 lineLength : 虛線寬度
 lineSpacing: 虛線間距
 lineColor  : 虛線顏色
 */
+ (void)drawDashLine:(UIView *)lineView
          lineLength:(int)lineLength
         lineSpacing:(int)lineSpacing
           lineColor:(UIColor *)lineColor {
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:lineView.bounds];
    [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame))];
    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    [shapeLayer setStrokeColor:lineColor.CGColor];
    [shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];
    [shapeLayer setLineJoin:kCALineJoinRound];
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:
                                    [NSNumber numberWithInt:lineLength],
                                    [NSNumber numberWithInt:lineSpacing], nil]];

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    CGPathAddLineToPoint(path, NULL, CGRectGetWidth(lineView.frame), 0);
    [shapeLayer setPath:path];
    CGPathRelease(path);

    [lineView.layer addSublayer:shapeLayer];
}

8. 把畫面存成圖片並存入相簿

用 renderInContext: 把整個 view 階層攤平成一張 UIImage,再寫入相簿。

- (void)save:(UIBarButtonItem *)sender {
    UIGraphicsBeginImageContext(self.hmView.bounds.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [self.hmView.layer renderInContext:ctx];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    UIImageWriteToSavedPhotosAlbum(image, NULL, NULL, NULL);
}

實務上若要正式上線,記得處理 iOS 的相簿權限請求,並實作 image:didFinishSavingWithError:contextInfo: 回呼掌握寫入結果。

9. 產生純色圖片(常用於高亮態背景)

+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

10. UIView 的座標轉換

四個方法分別處理 point 與 rect 的雙向轉換:

// point 由所在視圖轉到目標視圖
- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view;
// point 由 view 轉回當前視圖
- (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view;
// rect 由所在視圖轉到目標視圖
- (CGRect)convertRect:(CGRect)rect toView:(UIView *)view;
// rect 由 view 轉回當前視圖
- (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;

典型應用:controllerA 的 UITableView 裡有若干 cell,每個 cell 上有一顆 button,想知道 button 在 controllerA 座標系中的位置:

CGRect rc = [cell convertRect:cell.btn.frame toView:self.view];
// 或
CGRect rc = [self.view convertRect:cell.btn.frame fromView:cell];

// 已知 btn 時
CGRect rc = [btn.superview convertRect:btn.frame toView:self.view];
// 或
CGRect rc = [self.view convertRect:btn.frame fromView:btn.superview];

11. 顏色:RGB 與 16 進位

#define kRTColorWihRGB(R,G,B) [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:1.0]

#define kRTColorWithHEX(hex,opa) [UIColor colorWithRed:((float)((hex & 0XFF0000) >> 16))/255.0 \
                                             green:((float)((hex & 0X00FF00) >> 8))/255.0 \
                                              blue:((float)(hex & 0X0000FF))/255.0 \
                                             alpha:opa]

12. 數字加上千分位逗號

- (NSString *)formatNumber:(double)num {
    NSNumberFormatter *formatterCurrency = [[NSNumberFormatter alloc] init];
    formatterCurrency.numberStyle = NSNumberFormatterDecimalStyle;
    [formatterCurrency setMaximumFractionDigits:2];
    return [formatterCurrency stringFromNumber:@(num)];
}

13. 把科學記號還原成普通數字

NSString *str = @"1.2808245E7";
NSRange eSite = [str rangeOfString:@"E"];
// 把 E 前面的數字取出當底數
double fund = [[str substringWithRange:NSMakeRange(0, eSite.location)] doubleValue];
// 把 E 後面的數字取出當指數
double top = [[str substringFromIndex:eSite.location + 1] doubleValue];
double result = fund * pow(10.0, top);

14. 幾個型別與方法檢核

-(BOOL)isKindOfClass:(Class)classObj           // 是否為某類或其子類的實例
-(BOOL)isMemberOfClass:(Class)classObj         // 是否為某類的實例(不含子類)
-(BOOL)respondsToSelector:(SEL)selector        // 是否有指定名稱的方法
+(BOOL)instancesRespondToSelector:(SEL)selector // 該類的實例是否有此方法

前兩個用來判斷物件的身分,後兩個用來判斷能力。差別在於 respondsToSelector: 可以對實例與類別呼叫,而 instancesRespondToSelector: 只能對類別呼叫。

15. UIDatePicker 基本用法

UIDatePicker *dp = [[UIDatePicker alloc] init];
[dp setDate:[NSDate date] animated:YES];
[dp addTarget:self action:@selector(dateValueChange:) forControlEvents:UIControlEventValueChanged];

// 地區設定,影響顯示格式與星期用語
[dp setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];

// 取值時的格式化
NSDateFormatter *form = [[NSDateFormatter alloc] init];
[form setDateFormat:@"yyyy/MM/dd HH:mm"];
NSString *dateString = [form stringFromDate:dp.date];

dp.minuteInterval = 30;                                        // 最小間隔 30 分鐘
dp.minimumDate = [NSDate date];                                // 可選最小值
dp.maximumDate = [NSDate dateWithTimeIntervalSinceNow:60*60*24*31]; // 可選最大值

dp.datePickerMode = UIDatePickerModeTime;            // 時間
dp.datePickerMode = UIDatePickerModeDate;            // 日期
dp.datePickerMode = UIDatePickerModeDateAndTime;     // 日期 + 時間
dp.datePickerMode = UIDatePickerModeCountDownTimer;  // 倒數計時

小提醒:格式化字串裡月份應使用 MM,DD 代表的是「一年中的第幾天」,這是最常見的格式化錯誤之一。

補充:block 中記得 weak 化 self

在建立 block 之前把 self 做弱引用,否則容易形成循環引用,導致 controller 永遠無法釋放:

__weak MyController *weakSelf = self;
// 或
__weak __typeof(self) weakSelf = self;

若 block 內部需要強引用(例如要在 block 執行期間保證物件存活),可在 block 開頭再 strong 化一次,並在使用前判空——這就是常見的 weak-strong dance。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved