分享一些iOS开发实用的小技巧

2020-01-18 16:20:29刘景俊

1.设置navigationbar title颜色


 UIColor *whiteColor = [UIColor whiteColor];
NSDictionary *dic = [NSDictionary dictionaryWithObject:whiteColor forKey:NSForegroundColorAttributeName];
[self.navigationController.navigationBar setTitleTextAttributes:dic];

2.获取UIColor RGB


 UIColor *color = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
const CGFloat *components = CGColorGetComponents(color.CGColor);
NSLog(@"Red: %f", components[0]);
NSLog(@"Green: %f", components[1]);
NSLog(@"Blue: %f", components[2]);
NSLog(@"Alpha: %f", components[3]);

3.修改textField的placeholder的字体颜色、大小


 [self.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[self.textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

4.将color转为UIImage


 - (UIImage *)createImageWithColor:(UIColor *)color {
 CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
 UIGraphicsBeginImageContext(rect.size);
 CGContextRef context = UIGraphicsGetCurrentContext();
 CGContextSetFillColorWithColor(context, [color CGColor]);
 CGContextFillRect(context, rect);
 UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();
 return theImage;
}

5.加载启动图的时候隐藏statusbar

在info.plist中加入Status bar is initially hidden 设置为YES

ios10使用小技巧,ios小技巧,ios开发技巧

6.获取按钮title的size


/**
 * 获取按钮title的size
 */
- (CGFloat)getBtnTitleWidth:(UIButton*)btn {
 CGSize titleSize = [btn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:btn.titleLabel.font}];
 return titleSize;
}

7.设置Status bar颜色


UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, -20, ScreenWidth, 20)];[view setBackgroundColor:COLOR_APP_MAIN];
[viewController.navigationController.navigationBar addSubview:view];

8.json转dictionary,dictionary转json


+ (NSString*)dictionaryToJson:(NSDictionary *)dic {

 NSError *parseError = nil;

 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];

 return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

}

+(NSDictionary *)jsonToDic:(NSString*)jsonStr {
  NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
  NSError *err;
  NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
               options:NSJSONReadingMutableContainers
                error:&err];
  return dic;
}