1.字符串处理: 截取字符串
- -(NSString *)substringToIndex:(NSUInteger)to;
- 不包括index处字符
- 判断字符串长度,否则可能崩溃
2.在导航栏添加UIBarButtonItem时,在iOS7后会进行自动渲染
img = [img imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
3.遍历数组删除某个元素(不要forin正序遍历时删除,会崩溃)
- 逆序遍历,然后查找删除
NSEnumerator *enumerator = [array reverseObjectEnumerator];
//forin遍历
for (AddressPerson *groupName in enumerator) {
if ([[groupName group] isEqualToString:@"Zhangsan"]) {
[array removeObject:groupName];
}
}
- 定义一个副本,遍历副本找到想要删除的元素index,然后在原数组中删除对应的元素
4. 数组元素去重
- 利用NSSet的allObjects方法
NSSet *set = [NSSet setWithArray:dataArray];
NSLog(@"%@",[set allObjects]);
- 利用数组的containsObject来去除
NSMutableArray *listAry = [[NSMutableArray alloc]init];
for (NSString *str in dataArray) {
if (![listAry containsObject:str]) {
[listAry addObject:str];
}
}
NSLog(@"%@",listAry);
- 利用NSDictionary的AllKeys(AllValues)方法
NSArray *dataArray = @[@"2014-04-01",@"2014-04-02",@"2014-04-03",
@"2014-04-01",@"2014-04-02",@"2014-04-03",
@"2014-04-01",@"2014-04-03",@"2014-04-03",
@"2014-04-01",@"2014-04-02",@"2014-04-03",
@"2014-04-01",@"2014-04-02",@"2014-04-03",
@"2014-04-01",@"2014-04-02",@"2014-04-03",
@"2014-04-04",@"2014-04-06",@"2014-04-08",
@"2014-04-05",@"2014-04-07",@"2014-04-09",];
NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithCapacity:0];
for(NSString *str in dataArray)
{
[dic setValue:str forKey:str];
}
NSLog(@"%@",[dic allKeys]);
5. 如果设置了启动图片而没有生效,需要将原来的程序卸载在运行即可.
6.添加4s模拟器
/Applications(应用程序)/Xcode.app(显示包内容)/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/CoreSimulator/Profiles/Runtimes 后面两级目录需要自己创建
Xcode 显示包内容 Contents-->Developer-->Platforms-->iPhoneOS.platform-->DeviceSupport
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
7.通过状态栏判断当前的网络连接状态
/*
* 0 = No wifi or cellular
* 1 = 2G and earlier? (not confirmed)
* 2 = 3G? (not yet confirmed)
* 3 = 4G
* 4 = LTE
* 5 = Wifi
*/
- (int)dataNetworkTypeFromStatusBar
{
UIApplication *app = [UIApplication sharedApplication];
NSArray *subviews = [[[app valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
NSNumber *dataNetworkItemView = nil;
for (id subview in subviews) {
if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
dataNetworkItemView = subview;
break;
}
}
int netType = 0;
NSNumber * num = [dataNetworkItemView valueForKey:@"dataNetworkType"];
if (num == nil) {
netType = 0;
}else{
int n = [num intValue];
if (n == 0) {
netType = 0;
}else if (n == 1){
netType = 1;
}else if (n == 2){
netType = 2;
}else{
netType = 3;
}
}
return netType;
}
# import
# import
**获取运营商信息**
-(void)getcarrierName{
CTTelephonyNetworkInfo *telephonyInfo = [[CTTelephonyNetworkInfo alloc] init];
CTCarrier *carrier = [telephonyInfo subscriberCellularProvider];
NSString *currentCountry=[carrier carrierName];
NSLog(@"[carrier isoCountryCode]==%@,[carrier allowsVOIP]=%d,[carrier mobileCountryCode=%@,[carrier mobileCountryCode]=%@",[carrier isoCountryCode],[carrier allowsVOIP],[carrier mobileCountryCode],[carrier mobileNetworkCode]);
serverLabel.text=currentCountry;
}
8.搜索框添加 “广告”标签
- (void)addADFlagOnSearchBar {
NSString *key = [self.requestDict objectForKey:@"key"];
if (key && key.length > 0) {
self.searchBar.showsSearchResultsButton = NO;
} else {
self.searchBar.showsSearchResultsButton = YES;
NSString *imageName = (iPhone6Plus? @"xfList_AD_iPhone6plus_icon.png": @"xfList_AD_iPhone5_icon.png");
[self.searchBar setImage:[UIImage imageNamed:imageName] forSearchBarIcon:UISearchBarIconResultsList state:UIControlStateNormal];
UITextField *searchField = [self.searchBar valueForKey:@"_searchField"];
if (searchField) {
searchField.rightView.bounds = CGRectMake(0, 0, 27, 14);
searchField.rightViewMode = UITextFieldViewModeUnlessEditing;
}
[self.searchBar setPositionAdjustment:UIOffsetMake(5, 0) forSearchBarIcon:UISearchBarIconResultsList];
}
}
9.禁止手机睡眠 参考链接
UIApplication.shared.isIdleTimerDisabled = true
iOS8系统中,tableView最好实现下-tableView: heightForRowAtIndexPath:这个代理方法,要不然在iOS8中可能就会出现显示不全或者无法响应事件的问题
// 必须写的方法,和editActionsForRowAtIndexPath配对使用,里面什么不写也行
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
}
10.collectionView的内容小于其宽高的时候是不能滚动的,设置可以滚动:
collectionView.alwaysBounceHorizontal = YES;
collectionView.alwaysBounceVertical = YES;
11.强引用 / 弱引用????
#define WeakSelf(type) __weak typeof(type) weak##type = type; // weak
#define StrongSelf(type) __strong typeof(type) type = weak##type; // strong
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
12.image圆角
- (UIImage *)circleImage
{
// NO代表透明
UIGraphicsBeginImageContextWithOptions(self.size, NO, 1);
// 获得上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 添加一个圆
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
// 方形变圆形
CGContextAddEllipseInRect(ctx, rect);
// 裁剪
CGContextClip(ctx);
// 将图片画上去
[self drawInRect:rect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
+ (UIImage *)resizableImage:(NSString *)imageName
{
UIImage *image = [UIImage imageNamed:imageName];
CGFloat imageW = image.size.width;
CGFloat imageH = image.size.height;
return [image resizableImageWithCapInsets:UIEdgeInsetsMake(imageH * 0.5, imageW * 0.5, imageH * 0.5, imageW * 0.5) resizingMode:UIImageResizingModeStretch];
}
13.身份证号验证
- (BOOL)validateIdentityCard {
BOOL flag;
if (self.length <= 0) {
flag = NO;
return flag;
}
NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
return [identityCardPredicate evaluateWithObject:self];
}
14.拿到当前正在显示的控制器,不管是push进去的,还是present进去的都能拿到
- (UIViewController *)getVisibleViewControllerFrom:(UIViewController*)vc {
if ([vc isKindOfClass:[UINavigationController class]]) {
return [self getVisibleViewControllerFrom:[((UINavigationController*) vc) visibleViewController]];
}else if ([vc isKindOfClass:[UITabBarController class]]){
return [self getVisibleViewControllerFrom:[((UITabBarController*) vc) selectedViewController]];
} else {
if (vc.presentedViewController) {
return [self getVisibleViewControllerFrom:vc.presentedViewController];
} else {
return vc;
}
}
}
15.真机测试的时候报错:Could not launch "你的 App",process launch failed: Security
- 因为你的app没有上线,iOS9开始,需要手动信任Xcode生成的描述文件,打开手机设置->通用->描述文件->点击你的app的描述文件->点击信任
真机测试的时候报错:Could not find Developer Disk Image
- 这是因为你的设备系统版本大于Xcode能兼容的系统版本,比如你的设备是iOS10.3,而Xcode版本是8.2(Xcode8.2最大兼容iOS10.2),就会报这个错误。解决办法就是升级Xcode!
16.移除字符串中的空格和换行
+ (NSString *)removeSpaceAndNewline:(NSString *)str {
NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
return temp;
}
17.字符串是否为空
+ (BOOL)isEqualToNil:(NSString *)str {
return str.length <= 0 || [str isEqualToString:@""] || !str;
}
18.判断字符串中是否有空格
+ (BOOL)isBlank:(NSString *)str {
NSRange _range = [str rangeOfString:@" "];
if (_range.location != NSNotFound) {
//有空格
return YES;
} else {
//没有空格
return NO;
}
}
19.从NSURL中拿到链接字符串
NSString *urlString = myURL.absoluteString;
20.如果用addTarget:action:forControlEvents:方法为一个button添加了很多点击事件,在某个时刻想一次删除怎么办?只需要调用下边这句代码
[youButton removeTarget:nil action:nil forControlEvents:UIControlEventAllEvents];
21.tableViewCell分割线顶到头
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
[cell setSeparatorInset:UIEdgeInsetsZero];
[cell setLayoutMargins:UIEdgeInsetsZero];
cell.preservesSuperviewLayoutMargins = NO;
}
- (void)viewDidLayoutSubviews {
[self.tableView setSeparatorInset:UIEdgeInsetsZero];
[self.tableView setLayoutMargins:UIEdgeInsetsZero];
}
防止离屏渲染为image添加圆角
// image分类
- (UIImage *)circleImage
{
// NO代表透明
UIGraphicsBeginImageContextWithOptions(self.size, NO, 1);
// 获得上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 添加一个圆
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
// 方形变圆形
CGContextAddEllipseInRect(ctx, rect);
// 裁剪
CGContextClip(ctx);
// 将图片画上去
[self drawInRect:rect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
22.判断rect是否相等交叉
// 是否相交
if (CGRectIntersectsRect(rect1, rect2)) {
}
if (CGRectEqualToRect(rect1, rect2)) { // 两个区域相等
// do some
}
if (CGPointEqualToPoint(point1, point2)) { // 两个点相等
// do some
}
if (CGSizeEqualToSize(size1, size2)) { // 两个size相等
// do some
}
23.判断字符串是否为数字
NSCharacterSet *notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([str rangeOfCharacterFromSet:notDigits].location == NSNotFound)
{
// 是数字
} else
{
// 不是数字
}
23、判断一个view是否为另一个view的子视图
// 如果myView是self.view本身,也会返回yes
BOOL isSubView = [myView isDescendantOfView:self.view];
24.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;
}
25 字符串转数值问题
- 非纯数字的字符串转doublevalue floatvalue 都是 0
- 如和判断一个字符串是否为数字和小数点
- (BOOL)isPureNumandCharacters:(NSString *)string
{
NSCharacterSet *numberSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
string = [string stringByTrimmingCharactersInSet:numberSet];
if(string.length > 0)
{
return NO;
}
return YES;
}
26 字符串包含
- (BOOL)containsString:(NSString *)str
- str不能为nil,否则会崩溃
- API_AVAILABLE ios(8.0)