1、UILabel显示不同颜色字体
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:label.text];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];
label.attributedText = string;
2、比较两个CGRect/CGSize/CGPoint是否相等
if (CGRectEqualToRect(rect1, rect2)) { // 两个区域相等
// do some
}
if (CGPointEqualToPoint(point1, point2)) { // 两个点相等
// do some
}
if (CGSizeEqualToSize(size1, size2)) { // 两个size相等
// do some
}
3、比较两个NSDate相差多少小时
NSDate* date1 = someDate;
NSDate* date2 = someOtherDate;
NSTimeInterval distanceBetweenDates = [date1 timeIntervalSinceDate:date2];
double secondsInAnHour = 3600;
// 除以3600是把秒化成小时,除以60得到结果为相差的分钟数
NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;
4、查看系统所有字体
// 打印字体
for (id familyName in [UIFont familyNames]) {
NSLog(@"%@", familyName);
for (id fontName in [UIFont fontNamesForFamilyName:familyName]) NSLog(@" %@", fontName);
}
5、获取随机数
NSInteger i = arc4random();
srand((unsigned)time(0)); //不加这句每次产生的随机数不变
int i = rand() % 5;
//第二种
srandom(time(0));
int i = random() % 5;
//第三种 (好用)
int i = arc4random() % 5 ;
① rand()和random()实际并不是一个真正的伪随机数发生器,在使用之前需要先初始化随机种子,否则每次生成的随机数一样。
② arc4random() 是一个真正的伪随机算法,不需要生成随机种子,因为第一次调用的时候就会自动生成。而且范围是rand()的两倍。在iPhone中,RAND_MAX是0x7fffffff (2147483647),而arc4random()返回的最大值则是 0x100000000 (4294967296)。
精确度比较:arc4random() > random() > rand()
附:arc4random() 常用方法集合
//获取一个随机整数范围在:[0,100)包括0,不包括100
int x = arc4random() % 100;
//获取一个随机数范围在:[500,1000),包括500,不包括1000
int y = (arc4random() % 501) + 500;
//获取一个随机整数,范围在[from,to),包括from,不包括to
-(int)getRandomNumber:(int)from to:(int)to
{
return (int)(from + (arc4random() % (to – from + 1)));
} ```
6、获取随机数小数(0-1之间)
>#define ARC4RANDOM_MAX 0x100000000
double val = ((double)arc4random() / ARC4RANDOM_MAX);
7、判断一个字符串是否为数字
>NSCharacterSet *notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([str rangeOfCharacterFromSet:notDigits].location == NSNotFound) {
// 是数字
} else
{
// 不是数字
}
8、将一个view保存为pdf格式
>- (void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename{
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
[aView.layer renderInContext:pdfContext];
UIGraphicsEndPDFContext();
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
}
9、让一个view在父视图中心
>child.center = [parent convertPoint:parent.center fromView:parent.superview];
10、获取当前导航控制器下前一个控制器
>-(UIViewController *)backViewController {
NSInteger myIndex = [self.navigationController.viewControllers indexOfObject:self];
if ( myIndex != 0 && myIndex != NSNotFound ) {
return [self.navigationController.viewControllers objectAtIndex:myIndex-1];
} else {
return nil;
}
}
10、动画修改label上的文字
// 方法一
>CATransition *animation = [CATransition animation];
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.type = kCATransitionFade;
animation.duration = 0.75;
[self.label.layer addAnimation:animation forKey:@"kCATransitionFade"];
self.label.text = @"New";
// 方法二
>[UIView transitionWithView:self.label
duration:0.25f
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
self.label.text = @"Well done!";
} completion:nil];
// 方法三
>[UIView animateWithDuration:1.0
animations:^{
self.label.alpha = 0.0f;
self.label.text = @"newText";
self.label.alpha = 1.0f;
}];
11、获取屏幕方向
>UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if(orientation == 0) //Default orientation
//默认
else if(orientation == UIInterfaceOrientationPortrait)
//竖屏
else if(orientation == UIInterfaceOrientationLandscapeLeft)
// 左横屏
else if(orientation == UIInterfaceOrientationLandscapeRight)
//右横屏
12、图片的圆形处理
imageView.layer.masksToBounds = YES;
imageView.layer.cornerRadius = imageView.bounds.size.width * 0.5;
imageView.layer.borderWidth = 2;
imageView.layer.borderColor = [UIColor whiteColor].CGColor;
[cell.contentView addSubview:imageView];
13、隐藏UITextView/UITextField光标
`textField.tintColor = [UIColor clearColor];`
14、当UITextView/UITextField中没有文字时,禁用回车键
`textField.enablesReturnKeyAutomatically = YES;`
15、仿苹果抖动动画
```#define RADIANS(degrees) (((degrees) * M_PI) / 180.0)
-(void)startAnimate {
view.transform = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(-5));
[UIView animateWithDuration:0.25 delay:0.0 options:(UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse) animations:^ {
view.transform = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(5));
} completion:nil];
}```
```- (void)stopAnimate {
[UIView animateWithDuration:0.25 delay:0.0 options:(UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear) animations:^ {
view.transform = CGAffineTransformIdentity;
} completion:nil];```
16、 一些不常用的小方法
求数值的平方根
>int a = 12;
>NSLog(@“%d”,sqrt(a));
求数值的次方根
>int a =12;
>NSLog(@“%d”,pow(a));
//等待几秒
>sleep(3);//暂停3秒
17、时间戳的转换
获取系统时间戳
> NSDate* date1 = [NSDate date];
NSTimeInterval time1 =[date1 timeIntervalSince1970];
NSString *timeString = [NSString stringWithFormat:@"%.0f",time1];
NSLog(@"系统时间戳:%@",timeString);```
时间戳转换成时间
> NSTimeInterval time2 =[timeString doubleValue];
NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:time2];
NSLog(@"date2 = %@",date2);
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy/MM/dd"];
NSString *currentTime = [formatter stringFromDate:date2];
NSLog(@"当前时间:%@",currentTime);
NSLog(@"%@",date2);
```-(NSString*)getCurrentTime {
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyy--MM--dd--HH--mm--ss"];
NSString *dateTime = [formatter stringFromDate:[NSDate date]];
self.CurrentTime= dateTime;
NSLog(@"当前时间是===%@",_CurrentTime);
return _CurrentTime;
}```
//时间戳转换为正常时间格式
/** 时间戳的转换 */
> NSTimeInterval time=[时间戳字符串 doubleValue]+28800;//因为时差问题要加8小时 == 28800 sec
NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
NSLog(@"date:%@",[detaildate description]);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//设定时间格式,这里可以设置成自己需要的格式
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//返回的字符串就是时间戳
NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
18、设置UITextField光标位置
// textField需要设置的textField,index要设置的光标位置
>-(void)cursorLocation:(UITextField *)textField index:(NSInteger)index
{
NSRange range = NSMakeRange(index, 0);
UITextPosition *start = [textField positionFromPosition:[textField beginningOfDocument] offset:range.location];
UITextPosition *end = [textField positionFromPosition:start offset:range.length];
[textField setSelectedTextRange:[textField textRangeFromPosition:start toPosition:end]];
}
19、获取用户的IP地址
```//导入头文件
#import
#import
//方法调用
- (NSString *)getIPAddress {
NSString *address = @"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0) {
// Loop through linked list of interfaces
temp_addr = interfaces;
while(temp_addr != NULL) {
if(temp_addr->ifa_addr->sa_family == AF_INET) {
// Check if interface is en0 which is the wifi connection on the iPhone
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
// Get NSString from C String
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);
return address;```
20、Xcode报错报警 提示一堆file missing警告
```::此问题,是由于升级之后xcode找不到MAC隐藏文件引起的.
解决办法 : 打开终端输入 : defaults write com.apple.finder AppleShowAllFiles YES
敲击回车 , 再推出xcode 重新打开就行了.
此命令是显示Mac隐藏文件的. ```
21、调用系统功能 - 不是私有的
Wi-Fi: App-Prefs:root=WIFI
蓝牙: App-Prefs:root=Bluetooth
蜂窝移动网络: App-Prefs:root=MOBILE_DATA_SETTINGS_ID
个人热点: App-Prefs:root=INTERNET_TETHERING
运营商: App-Prefs:root=Carrier
通知: App-Prefs:root=NOTIFICATIONS_ID
通用: App-Prefs:root=General
通用-关于本机: App-Prefs:root=General&path=About
通用-键盘: App-Prefs:root=General&path=Keyboard
通用-辅助功能: App-Prefs:root=General&path=ACCESSIBILITY
通用-语言与地区: App-Prefs:root=General&path=INTERNATIONAL
通用-还原: App-Prefs:root=Reset
墙纸: App-Prefs:root=Wallpaper
Siri: App-Prefs:root=SIRI
隐私: App-Prefs:root=Privacy
定位: App-Prefs:root=LOCATION_SERVICES
Safari: App-Prefs:root=SAFARI
音乐: App-Prefs:root=MUSIC
音乐-均衡器: App-Prefs:root=MUSIC&path=com.apple.Music:EQ
照片与相机: App-Prefs:root=Photos
FaceTime: App-Prefs:root=FACETIME
22、手机号码验证最新号码段增加写入
```/*
*手机号验证
*/
+ (BOOL) isValidateMobile:(NSString *)mobileNum {
if (mobileNum.length != 11)
{
return NO;
}
/**
* 手机号码:
* 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9]
* 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
* 联通号段: 130,131,132,155,156,185,186,145,176,1709
* 电信号段: 133,153,180,181,189,177,1700
*/
NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-9]|8[0-9]|70)\\d{8}$";
/**
* 中国移动:China Mobile
* 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
*/
NSString *CM = @"(^1(3[0-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
/**
* 中国联通:China Unicom
* 130,131,132,155,156,185,186,145,176,1709
*/
NSString *CU = @"(^1(3[0-9]|4[5]|5[0-9]|7[0-9]|8[0-9])\\d{8}$)|(^1709\\d{7}$)";
/**
* 中国电信:China Telecom * 133,153,180,181,189,177,1700
*/
NSString *CT = @"(^1(33|53|77|8[019])\\d{8}$)|(^1700\\d{7}$)";
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;
}
}```
23、图片压缩
```+ (NSData *)zipNSDataWithImage:(UIImage *)sourceImage{
//进行图像尺寸的压缩
CGSize imageSize = sourceImage.size;//取出要压缩的image尺寸
CGFloat width = imageSize.width; //图片宽度
CGFloat height = imageSize.height; //图片高度
//1.宽高大于1280(宽高比不按照2来算,按照1来算)
if (width>1280) {
if (width>height) {
CGFloat scale = width/height;
height = 1280;
width = height*scale;
}else{
CGFloat scale = height/width;
width = 1280;
height = width*scale;
}
//2.高度大于1280
}else if(height>1280){
CGFloat scale = height/width;
width = 1280;
height = width*scale;
}else{
}
UIGraphicsBeginImageContext(CGSizeMake(width, height));
[sourceImage drawInRect:CGRectMake(0,0,width,height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//进行图像的画面质量压缩
NSData *data=UIImageJPEGRepresentation(newImage, 1.0);
if (data.length>100*1024) {
if (data.length>1024*1024) {//1M以及以上
data=UIImageJPEGRepresentation(newImage, 0.7);
}else if (data.length>512*1024) {//0.5M-1M
data=UIImageJPEGRepresentation(newImage, 0.8);
}else if (data.length>200*1024) {
//0.25M-0.5M
data=UIImageJPEGRepresentation(newImage, 0.9);
}
}
return data;
}```
24、十进制转换十六进制
>+(NSString *)ToHex:(long long int)tmpid
{
NSString *nLetterValue;
NSString *str =@"";
long long int ttmpig;
for (int i = 0; i<4; i++) {
ttmpig=tmpid%16;
tmpid=tmpid/16;
switch (ttmpig)
{
case 10:
nLetterValue =@"A";break;
case 11:
nLetterValue =@"B";break;
case 12:
nLetterValue =@"C";break;
case 13:
nLetterValue =@"D";break;
case 14:
nLetterValue =@"E";break;
case 15:
nLetterValue =@"F";break;
default:nLetterValue=[[NSString alloc]initWithFormat:@"%lli",ttmpig];
}
str = [nLetterValue stringByAppendingString:str];
}
return str;
}
25、//十六进制转换成十进制:
>+(NSInteger)ToNumber:(NSString *)hexstring{
NSInteger NewString =(NSInteger )strtoul([[hexstring substringWithRange:NSMakeRange(0, hexstring.length)]UTF8String],0,16);
return NewString;
}
26、比较两个UIImage是否相等
```- (BOOL)image:(UIImage *)image1 isEqualTo:(UIImage *)image2 {
NSData *data1 = UIImagePNGRepresentation(image1);
NSData *data2 = UIImagePNGRepresentation(image2);
return [data1 isEqual:data2];
}```
27、代码方式调整屏幕亮度
> brightness属性值在0-1之间,0代表最小亮度,1代表最大亮度
[[UIScreen mainScreen] setBrightness:0.5];
28、float数据取整四舍五入
```CGFloat f = 4.65;
NSLog(@"%d", (int)f); // 打印结果4
CGFloat f = 4.65;
NSLog(@"%d", (int)round(f)); // 打印结果5```
29、如何防止添加多个NSNotification观察者?
// 解决方案就是添加观察者之前先移除下这个观察者
```[[NSNotificationCenter defaultCenter] removeObserver:observer name:name object:object];
[[NSNotificationCenter defaultCenter] addObserver:observer selector:selector name:name object:object];```
30、将一个xib添加到另外一个xib上
```假设你的自定义view名字为CustomView,你需要在CustomView.m中重写
- (instancetype)initWithCoder:(NSCoder *)aDecoder` 方法,代码如下:
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])) {
[self addSubview:[[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil] objectAtIndex:0]];
}
return self;
}```
![1499658806305115.png](http://upload-images.jianshu.io/upload_images/6864638-9eac61d00cba85a2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
31、自动搜索功能,用户连续输入的时候不搜索,用户停止输入的时候自动搜索(我这里设置的是0.5s,可根据需求更改)
// 输入框文字改变的时候调用
```-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
// 先取消调用搜索方法
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(searchNewResult) object:nil];
// 0.5秒后调用搜索方法
[self performSelector:@selector(searchNewResult) withObject:nil afterDelay:0.5];
}```
32、手机震动
```简单实现手机震动,首先导入AudioToolBox.framework,在需要震动的文件中#import 。
调用震动的方法有2个
第一个
AudioServicesPlaySystemSoundWithCompletion(kSystemSoundID_Vibrate, ^{
//播放震动完事调用的块
});
第二个
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
两个方法都可以使用,直接调用就可以实现简单的震动。```
```/**
清理网页缓存
*/
- (void)deleteWebCache {
if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
NSSet *websiteDataTypes = [NSSet setWithArray:@[WKWebsiteDataTypeDiskCache,
//WKWebsiteDataTypeOfflineWebApplicationCache,
WKWebsiteDataTypeMemoryCache,
//WKWebsiteDataTypeLocalStorage,
//WKWebsiteDataTypeCookies,
//WKWebsiteDataTypeSessionStorage,
//WKWebsiteDataTypeIndexedDBDatabases,
//WKWebsiteDataTypeWebSQLDatabases
]];
//// Date from
NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
//// Execute
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
// Done
}];
} else {
NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
NSError *errors;
[[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
}
}```