欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS 常用方法

程序员文章站 2022-06-22 18:49:10
1.根据字体大小的计算出字符串的长和宽 CGSize nameSize = [name sizeWithAttributes:[NSDictionary dictiona...

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;