项目中最难的问题ios
2017-02-15 11:12:00 weixin_34368949 阅读数 52

迁移自开源中国

2013-4-27

  1. 客户端发送的请求数量和服务端接收的数量不一致。原因可能是服务端并发请求数量设置的过小。
  2. 利用GCD循环请求数据时小概率的引起程序崩溃。原因可能是两个线程同时对一个数据源进行了操作。
  3. 绘制分时、k线时线条模糊,举行时会出现四条边不一样粗细。原因就是IOS绘图机制的问题。推荐文章:http://my.oschina.net/lych0317/blog/126215
  4. 利用tableView的headerViewForSection:方法获取headerView时一直是nil。原因应该是设置headerView时利用- (UIView *)tableView: viewForHeaderInSection:的代理方法返回的UIView应该是UITableViewHeaderFooterView类型的,很多时候被他的返回值(UIView *)误导了。
  5. 由于项目比较大,页面多而且复杂,有时就需要从当前的responder通过nextResponder(一个甚至多个)找到深层次的VeiwController。推荐文章:http://my.oschina.net/lych0317/blog/113795
  6. 项目中需要用到循环刷新数据,利用NSTimer来实现,但是想在VC销毁时停掉timer(就是在dealloc方法中停掉),结果发现dealloc根本不调用,原本以为是引用计数没有减到0,可是问题不在此,而就在NSTimer这。结果在viewDidDisappear:停掉timer后就调用dealloc方法了。推荐文章:http://my.oschina.net/lych0317/blog/131295第一点
  7. 利用viewWithTag:寻找子View时,出现绝对性的错误,对象类型都不对。问题出现在设置的tag有重复,要注意的是子View在包括子View的子View的tag都不可以重复,所以建议另外创建一个文件专门设定tag,就像android中的R.java文件一样来确保tag的唯一。推荐文章:http://my.oschina.net/lych0317/blog/131295

2013-5-23

  1. 当新建工程调整原有目录结构时,提示警告:Warning: The Copy Bundle Resources build phase contains this target's Info.plist file 'ChartViewDemo/ChartViewDemo-Info.plist'.解决方法:http://blog.csdn.net/mideveloper/article/details/7790186
2017-04-14 16:31:00 weixin_33851177 阅读数 10

pragma mark 数组排序1

NSArray *array = [NSArray arrayWithObjects:@"2", @"3", @"1", @"4", nil nil];  
  
// 返回一个排好序的数组,原来数组的元素顺序不会改变  
// 指定元素的比较方法:compare:  
NSArray *array2 = [array sortedArrayUsingSelector:@selector(compare:)];  
NSLog(@"array2:%@", array2);  

pragma mark 数组排序2

Student *stu1 = [Student studentWithFirstname:@"MingJie" lastname:@"Li"];  
Student *stu2 = [Student studentWithFirstname:@"LongHu" lastname:@"Huang"];  
Student *stu3 = [Student studentWithFirstname:@"LianJie" lastname:@"Li"];  
Student *stu4 = [Student studentWithFirstname:@"Jian" lastname:@"Xiao"];  
NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3, stu4, nil nil];  
// 指定排序的比较方法  
NSArray *array2 = [array sortedArrayUsingSelector:@selector(compareStudent:)];  
NSLog(@"array2:%@", array2);  

}

  • (NSComparisonResult)compareStudent:(Student *)stu {
    // 先按照姓排序
    NSComparisonResult result = [self.lastname compare:stu.lastname];
    // 如果有相同的姓,就比较名字
    if (result == NSOrderedSame) {
    result = [self.firstname compare:stu.firstname];
    }
    return result;

pragma mark 数组排序3

Student *stu1 = [Student studentWithFirstname:@"MingJie" lastname:@"Li"];  
Student *stu2 = [Student studentWithFirstname:@"LongHu" lastname:@"Huang"];  
Student *stu3 = [Student studentWithFirstname:@"LianJie" lastname:@"Li"];  
Student *stu4 = [Student studentWithFirstname:@"Jian" lastname:@"Xiao"];  
NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3, stu4, nil nil];  
  
// 利用block进行排序  
NSArray *array2 = [array sortedArrayUsingComparator:  
 ^NSComparisonResult(Student *obj1, Student *obj2) {  
     // 先按照姓排序  
     NSComparisonResult result = [obj1.lastname compare:obj2.lastname];  
     // 如果有相同的姓,就比较名字  
     if (result == NSOrderedSame) {  
         result = [obj1.firstname compare:obj2.firstname];  
     }  
       
     return result;  
}];  
  
NSLog(@"array2:%@", array2);  

pragma mark 数组排序4-高级排序

Student *stu1 = [Student studentWithFirstname:@"MingJie" lastname:@"Li" bookName:@"book1"];  
Student *stu2 = [Student studentWithFirstname:@"LongHu" lastname:@"Huang" bookName:@"book2"];  
Student *stu3 = [Student studentWithFirstname:@"LianJie" lastname:@"Li" bookName:@"book2"];  
Student *stu4 = [Student studentWithFirstname:@"Jian" lastname:@"Xiao" bookName:@"book1"];  
NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3, stu4, nil nil];  
  
// 1.先按照书名进行排序  
// 这里的key写的是@property的名称  
NSSortDescriptor *bookNameDesc = [NSSortDescriptor sortDescriptorWithKey:@"book.name" ascending:YES];  
// 2.再按照姓进行排序  
NSSortDescriptor *lastnameDesc = [NSSortDescriptor sortDescriptorWithKey:@"lastname" ascending:YES];  
// 3.再按照名进行排序  
NSSortDescriptor *firstnameDesc = [NSSortDescriptor sortDescriptorWithKey:@"firstname" ascending:YES];  
// 按顺序添加排序描述器  
NSArray *descs = [NSArray arrayWithObjects:bookNameDesc, lastnameDesc, firstnameDesc, nil nil];  
  
NSArray *array2 = [array sortedArrayUsingDescriptors:descs];  
  
NSLog(@"array2:%@", array2);
2014-03-13 14:33:21 panderman 阅读数 7097
一、客户端发送的请求数量和服务端接收的数量不一致。原因可能是服务端并发请求数量设置的过小。
二、利用循环请求数据时小概率的引起程序崩溃。原因可能是两个线程同时对一个数据源进行了操作。
三、绘制分时、k线时线条模糊,举行时会出现四条边不一样粗细。原因就是IOS绘机制的问题。
四、利用tableView的headerViewForSection:方法获取headerView时一直是nil。原因应该是设置headerView时利用- (UIView *)tableView: viewForHeaderInSection:的代理方法返回的UIView应该是UITableViewHeaderFooterView类型的,很多时候被他的返回值(UIView *)误导了。
五、由于项目比较大,页面多而且复杂,有时就需要从当前的responder通过nextResponder(一个甚至多个)找到深层次的VeiwController。
六、项目中需要用到循环刷新数据,利用NSTimer来实现,但是想在VC销毁时停掉timer(就是在dealloc方法中停掉),结果发现dealloc根本不调用,原本以为是引用计数没有减到0,可是问题不在此,而就在NSTimer这。结果在viewDidDisappear:停掉timer后就调用dealloc方法了。
七、利用viewWithTag:寻找子View时,出现绝对性的错误,对象类型都不对。问题出现在设置的tag有重复,要注意的是子View在包括子View的子View的tag都不可以重复,所以建议另外创建一个文件专门设定tag,就像android中的R.java文件一样来确保tag的唯一。
2016-06-03 11:53:00 weixin_33698043 阅读数 37

1、做推送的时候注册通知,收到如下注册通知失败的消息:

  code=3000 NSLocalizedDescription=未找到应用程序的“aps-environment”的授权字符串

原因:
code=3000是由于iPhone上的配置文件的app identity是带通配符的,而推送不能用带通配符的

解决:

1.去Provisioning里面生成新的Profile,配置的app id是不带通配符的,与项目的bundleID 一样。
2.删除Xcode里面原来的push profile(如果没有就不用删除)再次双击新下载的profile(mobileprovision文件)
3.在项目的target里面选择新的profile然后编译

2、iOS去掉导航栏navigationBar下的横线

//去除导航栏下方的横线

    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor appNavigationBarColor]]
                       forBarPosition:UIBarPositionAny
                           barMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];

3、iOS 隐藏/去掉 导航栏返回按钮中的文字

最近iOS项目中要求导航栏的返回按钮只保留那个箭头,去掉后边的文字,在网上查了一些资料,最简单且没有副作用的方法就是

[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
 forBarMetrics:UIBarMetricsDefault];

4、集成支付宝SDK时的错误

问题:app集成支付宝报错:"openssl/asn1.h file not found"

解决办法:在自己工程文件夹里建一个文件夹,随便起什么名字。把支付宝所需要的东西都拷贝进去,然后add files,然后找到TARGETS-Build Settings,在里面找到如下位置


838624-6743feb7e8ade496.png
解决

5、自定义UISearchBar(修改placeHolder文字颜色,修改_searchField文字颜色,修改放大镜图片等)

838624-4adb3a59eb0473af.jpg
自定义UISearchBar
//修改背景图片,隐藏边框
[_searchBar setBackgroundImage:[UIImage imageWithColor:[UIColor clearColor]]];
_searchBar.placeholder = @"新房、二手房、租房";

//获取searchBar里面的TextField
UITextField *searchField = [_searchBar valueForKey:@"_searchField"];
//更改searchBar 中PlaceHolder 字体颜色
[searchField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
//更改searchBar输入文字颜色
searchField.textColor= [UIColor whiteColor];
//设置搜索框中TextField的背景图
[_searchBar setSearchFieldBackgroundImage:[UIImage imageWithColor:[UIColor colorWithWhite:1 alpha:0.2] size:CGSizeMake(200, 30) andRoundSize:15] forState:UIControlStateNormal];

//方法1、修改放大镜图片
[self.searchBar setImage:[UIImage imageNamed:@"search"] 
        forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
//方法2、修改放大镜
UIImage *image = [UIImage imageNamed:@"search"];
UIImageView *iconView = [[UIImageView alloc] initWithImage:image];
iconView.frame = CGRectMake(0, 0, image.size.width , image.size.height);
searchField.leftView = iconView;

UISearchBar详细的属性介绍

2018-11-22 00:25:00 weixin_33720078 阅读数 11

iOS项目常用效果

  1. 改变 UITextField 占位文字的颜色
[textField setValue:[UIcolor redColor] forKeyPath:@"_placeholderLabel.textColor"];
  1. 禁止横屏 在AppDelegate中使用
 - (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window  {  
     return UIInterfaceOrientationMaskPortrait;  
}

3、修改状态栏颜色 (默认黑色,修改为白色)

1. 在 Info.plist 中设置 UIViewControllerBasedStatusBarAppearance  为NO

2. 在需要改变状态栏颜色的 AppDelegate 中在 didFinishLaunchingWithOptions 方法中增加: 
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

3.如果需要在单个ViewController中添加,在ViewDidLoad方法中增加:
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

4、模糊效果

UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
UIVisualEffectView *test = [[UIVisualEffectView alloc] initWithEffect:effect];
test.frame = self.view.bounds;
test.alpha = 0.5;
[self.view addSubview:test];

5、强制横屏代码

- (BOOL)shouldAutorotate{
    //是否支持转屏
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
   //支持哪些转屏方向
    return UIInterfaceOrientationMaskLandscape;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationLandscapeRight;
}

- (BOOL)prefersStatusBarHidden{
    return NO;
}

6、在状态栏显示有网络请求的提示器

  [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

7、相对路径

    $(SRCROOT)/

8、视图是否自动(只是把第一个自动)向下挪64

 self.automaticallyAdjustsScrollViewInsets = NO; //不让系统帮咱们把scrollView及其子类的视图向下调整64

9、 隐藏手机的状态栏

-(BOOL)prefersStatusBarHidden {
    return YES;
}

10、代理的安全保护【判断是否有代理,和代理是否执行了代理方法】

if (self.delegate && [self.delegate respondsToSelector:@selector(passValueWithArray:)]) {
    // make you codes
}

11、在ARC工程中导入MRC的类和在MRC工程中导入ARC的类

在ARC工程中导入MRC的类  我们选中工程->选中targets中的工程,然后选中Build Phases->在导入的类后边加入标记 -  fno-objc-arc

在MRC工程中导入ARC的类 路径与上面一致,在该类后面加上标记 -fobjc-arc

12、通过 2D 仿射函数实现小的动画效果(变大缩小) --可用于自定义pageControl 中

[UIView animateWithDuration:0.3 animations:^{
    imageView.transform = CGAffineTransformMakeScale(2, 2);
} completion:^(BOOL finished) {
    imageView.transform = CGAffineTransformMakeScale(1.0, 1.0);
}];

13、查看系统所有字体

for (id familyName in [UIFont familyNames]) {
    NSLog(@"%@", familyName);
    for (id fontName in [UIFont fontNamesForFamilyName:familyName])         
      NSLog(@"  %@", fontName);
}

14、判断一个字符串是否为数字

NSCharacterSet *notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([str rangeOfCharacterFromSet:notDigits].location == NSNotFound){// 是数字

} else {// 不是数字

}   

15、将一个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);
}

16、让一个view在父视图中心

child.center = [parent convertPoint:parent.center   fromView:parent.superview];

17、获取当前导航控制器下前一个控制器

- (UIViewController *)backViewController{
    NSInteger myIndex = [self.navigationController.viewControllers indexOfObject:self];
    if ( myIndex != 0 && myIndex != NSNotFound ) {
        return [self.navigationController.viewControllers objectAtIndex:myIndex-1];
    } else {
        return nil;
    }
}

18、保存UIImage到本地

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];
[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];

19、键盘上方增加工具栏

UIToolbar *keyboardDoneButtonView = [[UIToolbar alloc] init];
[keyboardDoneButtonView sizeToFit];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self                                                          action:@selector(doneClicked:)];
[keyboardDoneButtonView setItems:[NSArray arrayWithObjects:doneButton, nil]];
txtField.inputAccessoryView = keyboardDoneButtonView;

20、在image上绘制文字并生成新的image

 UIFont *font = [UIFont boldSystemFontOfSize:12];
 UIGraphicsBeginImageContext(image.size);
 [image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];
 CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height);
 [[UIColor whiteColor] set];
 [text drawInRect:CGRectIntegral(rect) withFont:font]; 
 UIImage *newImage =    UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();

21、判断一个view是否为另一个view的子视图

 //如果myView是self.view本身,也会返回yes
BOOL isSubView = [myView isDescendantOfView:self.view];

22、判断一个字符串是否包含另一个字符串

// 方法一、这种方法只适用于iOS8之后,如果是配iOS8之前用方法二
if ([str containsString:otherStr]) NSLog(@"包含");

// 方法二
NSRange range = [str rangeOfString:otherStr];
if (range.location != NSNotFound) NSLog(@"包含");

23、判断某一行的cell是否已经显示

CGRect cellRect = [tableView rectForRowAtIndexPath:indexPath];
BOOL completelyVisible = CGRectContainsRect(tableView.bounds, cellRect);

24、让导航控制器pop回指定的控制器

NSMutableArray *allViewControllers = [NSMutableArray arrayWithArray:    [self.navigationController viewControllers]];
for (UIViewController *aViewController in allViewControllers) {
    if ([aViewController isKindOfClass:[RequiredViewController class]]) {
        [self.navigationController popToViewController:aViewController animated:NO];
        break;
    }
}

25、获取屏幕方向

UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;

if(orientation == 0) //默认
else if(orientation == UIInterfaceOrientationPortrait)//竖屏
else if(orientation == UIInterfaceOrientationLandscapeLeft) // 左横屏
else if(orientation == UIInterfaceOrientationLandscapeRight)//右横屏

26、UIWebView添加单击手势不响应

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(webViewClick)];
tap.delegate = self;
 [_webView addGestureRecognizer:tap];

// 因为webView本身有一个单击手势,所以再添加会造成手势冲突,从而不响应。需要绑定手势代理,并实现下边的代理方法
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}

27、获取手机RAM容量

// 需要导入#import
mach_port_t host_port;
mach_msg_type_number_t host_size;
vm_size_t pagesize;

 host_port = mach_host_self();
 host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
 host_page_size(host_port, &pagesize);

 vm_statistics_data_t vm_stat;

   if (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size) != KERN_SUCCESS) {
        NSLog(@"Failed to fetch vm statistics");
   }

  /* Stats in bytes */
  natural_t mem_used = (vm_stat.active_count +
                          vm_stat.inactive_count +
                          vm_stat.wire_count) * pagesize;
  natural_t mem_free = vm_stat.free_count * pagesize;
  natural_t mem_total = mem_used + mem_free;
  NSLog(@"已用: %u 可用: %u 总共: %u", mem_used, mem_free, mem_total);

28、地图上两个点之间的实际距离

// 需要导入#import   位置A、B
CLLocation *locA = [[CLLocation alloc] initWithLatitude:34 longitude:113];
CLLocation *locB = [[CLLocation alloc] initWithLatitude:31.05 longitude:121.76];
// CLLocationDistance求出的单位为米
CLLocationDistance distance = [locA distanceFromLocation:locB];

29、在应用中打开设置的某个界面

// 打开设置->通用
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=General"]];

// 以下是设置其他界面

prefs:root=General&path=About
prefs:root=General&path=ACCESSIBILITY
prefs:root=AIRPLANE_MODE
prefs:root=General&path=AUTOLOCK
prefs:root=General&path=USAGE/CELLULAR_USAGE
prefs:root=Brightness
prefs:root=Bluetooth
prefs:root=General&path=DATE_AND_TIME
prefs:root=FACETIME
prefs:root=General
prefs:root=General&path=Keyboard
prefs:root=CASTLE
prefs:root=CASTLE&path=STORAGE_AND_BACKUP
prefs:root=General&path=INTERNATIONAL
prefs:root=LOCATION_SERVICES
prefs:root=ACCOUNT_SETTINGS
prefs:root=MUSIC
prefs:root=MUSIC&path=EQ
prefs:root=MUSIC&path=VolumeLimit
prefs:root=General&path=Network
prefs:root=NIKE_PLUS_IPOD
prefs:root=NOTES
prefs:root=NOTIFICATIONS_ID
prefs:root=Phone
prefs:root=Photos
prefs:root=General&path=ManagedConfigurationList
prefs:root=General&path=Reset
prefs:root=Sounds&path=Ringtone
prefs:root=Safari
prefs:root=General&path=Assistant
prefs:root=Sounds
prefs:root=General&path=SOFTWARE_UPDATE_LINK
prefs:root=STORE
prefs:root=TWITTER
prefs:root=FACEBOOK
prefs:root=General&path=USAGE prefs:root=VIDEO
prefs:root=General&path=Network/VPN
prefs:root=Wallpaper
prefs:root=WIFI
prefs:root=INTERNET_TETHERING
prefs:root=Phone&path=Blocked
prefs:root=DO_NOT_DISTURB

30、监听scrollView是否滚动到了顶部/底部

-(void)scrollViewDidScroll: (UIScrollView*)scrollView{
    float scrollViewHeight = scrollView.frame.size.height;
    float scrollContentSizeHeight = scrollView.contentSize.height;
    float scrollOffset = scrollView.contentOffset.y;

    if (scrollOffset == 0)
    {
        // 滚动到了顶部
    }
    else if (scrollOffset + scrollViewHeight == scrollContentSizeHeight)
    {
        // 滚动到了底部
    }
}

31、从导航控制器中删除某个控制器

// 方法一、知道这个控制器所处的导航控制器下标
NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];
[navigationArray removeObjectAtIndex: 2]; 
self.navigationController.viewControllers = navigationArray;

// 方法二、知道具体是哪个控制器
NSArray* tempVCA = [self.navigationController viewControllers];
for(UIViewController *tempVC in tempVCA){
    if([tempVC isKindOfClass:[urViewControllerClass class]])
    {
        [tempVC removeFromParentViewController];
    }
}

32、触摸事件类型

UIControlEventTouchCancel 取消控件当前触发的事件
UIControlEventTouchDown 点按下去的事件
UIControlEventTouchDownRepeat 重复的触动事件
UIControlEventTouchDragEnter 手指被拖动到控件的边界的事件
UIControlEventTouchDragExit 一个手指从控件内拖到外界的事件
UIControlEventTouchDragInside 手指在控件的边界内拖动的事件
UIControlEventTouchDragOutside 手指在控件边界之外被拖动的事件
UIControlEventTouchUpInside 手指处于控制范围内的触摸事件
UIControlEventTouchUpOutside 手指超出控制范围的控制中的触摸事件

33、比较两个UIImage是否相等

- (BOOL)image:(UIImage *)image1 isEqualTo:(UIImage *)image2{
    NSData *data1 = UIImagePNGRepresentation(image1);
    NSData *data2 = UIImagePNGRepresentation(image2);

    return [data1 isEqual:data2];
}

34、代码方式调整屏幕亮度

// brightness属性值在0-1之间,0代表最小亮度,1代表最大亮度
[[UIScreen mainScreen] setBrightness:0.5];

35、根据经纬度获取城市等信息

// 创建经纬度
CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
//创建一个译码器
CLGeocoder *cLGeocoder = [[CLGeocoder alloc] init];
[cLGeocoder reverseGeocodeLocation:userLocation completionHandler:^(NSArray *placemarks, NSError *error) {
    CLPlacemark *place = [placemarks objectAtIndex:0];
    // 位置名
    NSLog(@"name,%@",place.name);
    // 街道
    NSLog(@"thoroughfare,%@",place.thoroughfare);
    // 子街道
    NSLog(@"subThoroughfare,%@",place.subThoroughfare);
    // 市
    NSLog(@"locality,%@",place.locality);
    // 区
    NSLog(@"subLocality,%@",place.subLocality); 
    // 国家
    NSLog(@"country,%@",place.country);
    }
}];

36、如何防止添加多个NSNotification观察者?

// 解决方案就是添加观察者之前先移除下这个观察者
[[NSNotificationCenter defaultCenter] removeObserver:observer name:name object:object];
[[NSNotificationCenter defaultCenter] addObserver:observer selector:selector name:name object:object];

37、处理字符串,使其首字母大写

NSString *str = @"abcdefghijklmn";
 NSString *resultStr;
if (str && str.length > 0) {
     resultStr = [str stringByReplacingCharactersInRange:NSMakeRange(0,1)   withString:[[str substringToIndex:1] capitalizedString]];
}
NSLog(@"%@", resultStr);

38、获取字符串中的数字

- (NSString *)getNumberFromStr:(NSString *)str{
     NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
     return [[str componentsSeparatedByCharactersInSet:nonDigitCharacterSet] componentsJoinedByString:@""];
}

39、为UIView的某个方向添加边框

    - (void)wzb_addBorder:(WZBBorderDirectionType)direction color:(UIColor *)color width:(CGFloat)width{
    CALayer *border = [CALayer layer];
    border.backgroundColor = color.CGColor;
    switch (direction) {
        case WZBBorderDirectionTop:
        {
            border.frame = CGRectMake(0.0f, 0.0f, self.bounds.size.width, width);
        }
            break;
        case WZBBorderDirectionLeft:
        {
            border.frame = CGRectMake(0.0f, 0.0f, width, self.bounds.size.height);
        }
            break;
        case WZBBorderDirectionBottom:
        {
            border.frame = CGRectMake(0.0f, self.bounds.size.height - width, self.bounds.size.width, width);
        }
            break;
        case WZBBorderDirectionRight:
        {
            border.frame = CGRectMake(self.bounds.size.width - width, 0, width, self.bounds.size.height);
        }
            break;
        default:
            break;
    }
    [self.layer addSublayer:border];
}

40、自动搜索功能,用户连续输入的时候不搜索,用户停止输入的时候自动搜索(我这里设置的是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];
}

41、修改UISearchBar的占位文字颜色

// 方法一(推荐使用)
UITextField *searchField = [searchBar valueForKey:@"_searchField"];
[searchField setValue:[UIColor blueColor] forKeyPath:@"_placeholderLabel.textColor"];

// 方法二(已过期)
[[UILabel appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor redColor]];
    
// 方法三(已过期)
NSDictionary *placeholderAttributes = @{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue" size:15],};
NSAttributedString *attributedPlaceholder = [[NSAttributedString alloc] initWithString:searchBar.placeholder attributes:placeholderAttributes];
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setAttributedPlaceholder:attributedPlaceholder];

42、动画执行removeFromSuperview

[UIView animateWithDuration:0.2
                animations:^{
                     view.alpha = 0.0f;
                } completion:^(BOOL finished){
                    [view removeFromSuperview];
  }];

43、修改image颜色

UIImage *image = [UIImage imageNamed:@"test"];
imageView.image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClipToMask(context, rect, image.CGImage);
CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]);
CGContextFillRect(context, rect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIImage *flippedImage = [UIImage imageWithCGImage:img.CGImage scale:1.0 orientation: UIImageOrientationDownMirrored];
imageView.image = flippedImage;

44、利用runtime获取一个类所有属性

- (NSArray *)allPropertyNames:(Class)aClass{
   unsigned count;
   objc_property_t *properties = class_copyPropertyList(aClass, &count);

   NSMutableArray *rv = [NSMutableArray array];

   unsigned i;
   for (i = 0; i < count; i++) {
      objc_property_t property = properties[i];
      NSString *name = [NSString stringWithUTF8String:property_getName(property)];
      [rv addObject:name];
   }
  free(properties);
   return rv;
}

45、让push跳转动画像modal跳转动画那样效果(从下往上推上来)

- (void)push{
    TestViewController *vc = [[TestViewController alloc] init];
    vc.view.backgroundColor = [UIColor redColor];
    CATransition* transition = [CATransition animation];
    transition.duration = 0.4f;
    transition.type = kCATransitionMoveIn;
    transition.subtype = kCATransitionFromTop;
    [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
    [self.navigationController pushViewController:vc animated:NO];
}

- (void)pop{
    CATransition* transition = [CATransition animation];
    transition.duration = 0.4f;
    transition.type = kCATransitionReveal;
    transition.subtype = kCATransitionFromBottom;
    [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
    [self.navigationController popViewControllerAnimated:NO];
}

1.强制旋转因为在做ipad横版shi'pi

博文 来自: Ysam1983
没有更多推荐了,返回首页