這篇把日常開發中反覆要查的零碎方法整理在一起,方便隨時翻閱。
CGSize nameSize = [name sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14], NSFontAttributeName, nil]];
輸入格式為 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];
}
做法是在按鈕與系統按鈕之間塞一個寬度為負值的 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];
NSIndexPath *idxPath = [NSIndexPath indexPathForRow:5 inSection:0];
[self.tableView scrollToRowAtIndexPath:idxPath
atScrollPosition:UITableViewScrollPositionMiddle
animated:NO];
高度給 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;
}
用 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;
}
提醒:號段規則會隨時間變動,這類正則最好集中管理並定期更新,別散落在各個專案檔案裡。
用 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];
}
用 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: 回呼掌握寫入結果。
+ (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;
}
四個方法分別處理 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];
#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]
- (NSString *)formatNumber:(double)num {
NSNumberFormatter *formatterCurrency = [[NSNumberFormatter alloc] init];
formatterCurrency.numberStyle = NSNumberFormatterDecimalStyle;
[formatterCurrency setMaximumFractionDigits:2];
return [formatterCurrency stringFromNumber:@(num)];
}
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);
-(BOOL)isKindOfClass:(Class)classObj // 是否為某類或其子類的實例 -(BOOL)isMemberOfClass:(Class)classObj // 是否為某類的實例(不含子類) -(BOOL)respondsToSelector:(SEL)selector // 是否有指定名稱的方法 +(BOOL)instancesRespondToSelector:(SEL)selector // 該類的實例是否有此方法
前兩個用來判斷物件的身分,後兩個用來判斷能力。差別在於 respondsToSelector: 可以對實例與類別呼叫,而 instancesRespondToSelector: 只能對類別呼叫。
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 之前把 self 做弱引用,否則容易形成循環引用,導致 controller 永遠無法釋放:
__weak MyController *weakSelf = self; // 或 __weak __typeof(self) weakSelf = self;
若 block 內部需要強引用(例如要在 block 執行期間保證物件存活),可在 block 開頭再 strong 化一次,並在使用前判空——這就是常見的 weak-strong dance。