1.根據字體大小的計算出字符串的長和寬
CGSize nameSize = [name sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14],NSFontAttributeName, nil]];
2.通過生日計算年齡
// calculate age by birthday // birthday : YYYYMMDD // age: *歲*個月*天 - (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]; NSString *result = [NSString stringWithFormat:@"%li歲%li個月%li天",year,month,day]; return result; }
3.為右邊的導航按鈕設置彈簧距離
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); UIBarButtonItem* rightBtnItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn]; [rightBtn addTarget:self action:@selector(attentionBtnClick:) forControlEvents:UIControlEventTouchUpInside]; 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.給定寬度和字體大小計算字符串的高度
- (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.檢測是否是手機號碼
-(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}$"; //中國移動:China Mobile NSString*CM=@"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$"; // 中國聯通:China Unicom NSString*CU=@"^1(3[0-2]|5[256]|8[56])\\d{8}$"; // 中國電信:China Telecom 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; }else{ return NO; } }
7.怎麼畫虛線
- (instancetype)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { [self drawRect:frame]; } return self; } -(void)drawRect:(CGRect)rect{ // self.layer.cornerRadius = 10; 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]; // 設置虛線顏色為blackColor [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.把圖片保存到相冊中
- (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); }
9.創建單一顏色的圖片然後設置UIControlStateHighlighted狀態
+ (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由point所在視圖轉換到目標視圖view中,返回在目標視圖view中的像素值 - (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view; // 將像素point從view中轉換到當前視圖中,返回在當前視圖中的像素值 - (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view; // 將rect由rect所在視圖轉換到目標視圖view中,返回在目標視圖view中的rect - (CGRect)convertRect:(CGRect)rect toView:(UIView *)view; // 將rect從view中轉換到當前視圖中,返回在當前視圖中的rect - (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view; // controllerA 中有一個UITableView, UITableView裡有多行UITableVieCell,cell上放有一個button // 在controllerA中實現: CGRect rc = [cell convertRect:cell.btn.frame toView:self.view]; 或 CGRect rc = [self.view convertRect:cell.btn.frame fromView:cell]; // 此rc為btn在controllerA中的rect 或當已知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"]; double fund = [[str substringWithRange:NSMakeRange(0, eSite.location)] doubleValue]; //把E前面的數截取下來當底數 double top = [[str substringFromIndex:eSite.location + 1] doubleValue]; //把E後面的數截取下來當指數 double result = fund * pow(10.0, top); }
14.一些判斷的方法
-(BOOL) isKindOfClass: classObj 用來判斷是否是某個類或其子類的實例 -(BOOL) isMemberOfClass: classObj 用來判斷是否是某個類的實例 -(BOOL) respondsToSelector: selector 用來判斷是否有以某個名字命名的方法(被封裝在一個selector的對象裡傳遞) +(BOOL) instancesRespondToSelector: selector 用來判斷實例是否有以某個名字命名的方法. 和上面一個不同之處在於, 前面這個方法可以用在實例和類上,而此方法只能用在類上.
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; // 倒計時模式
創建block匿名函數之前一般需要對self進行weak化,否則造成循環引用無法釋放controller:
__weak MyController *weakSelf = self 或者 __weak __typeof(self) weakSelf = self;