iOS 开发杂记

抛出异常

NSException* ex = [NSException exceptionWithName:@"name" reason:@"reason" userInfo:nil];
[ex raise];

UILabel文字添加删除线

    NSAttributedString* attrStr =
        [[NSAttributedString alloc] initWithString:@"ddddd"
                                        attributes:
                                            @{ NSFontAttributeName : [UIFont systemFontOfSize:20.f],
                                                NSForegroundColorAttributeName : [UIColor redColor],
                                                NSStrikethroughStyleAttributeName : @(NSUnderlineStyleSingle | NSUnderlinePatternSolid),
                                                NSStrikethroughColorAttributeName : [UIColor blueColor] }];
    self.label.attributedText = [attrStr copy];

自定义控件的数据源设置

自定义控件应该自己定义相关的数据源,
然后其他数据源想要使用这个自定义控件,
就把自定义控件的模型放到数据源模型中,
然后通过setValue :forKey :来进行对自定义控件的模型赋值。

NSString

//去掉空格
NSString* _titleLabelOutSpace = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
//NSString ->NSInteger
[_titleLabelOutSpace integerValue];

NSArray

//NSString  NSArray  互转
NSArray *arr = [@"a,b,c" componentsSeparatedByString:@","];


- (void)hasString:(NSString*)str1 string2:(NSString*)str2
{
    NSString* string1 = str1;
    NSString* string2 = str2;
    NSRange range = [string1 rangeOfString:string2];
    NSUInteger location = range.location;
    NSUInteger length = range.length;
    NSString* astring = [[NSString alloc] initWithString:[NSString stringWithFormat:@"Location:%zd,Leight:%zd", location, length]];
    NSLog(@"astring:%@", astring);
}
    [self hasString:@"1111111" string2:@"2"];
   //astring:Location:9223372036854775807, length:0
    [self hasString:@"11111112" string2:@"2"];
   //astring:Location:8,Leight:1
可以根据length来判断是否有字段

数组排序

[self.HelpManager.PublishScopeList sortedArrayUsingComparator:^NSComparisonResult(PublishScopeListModel* obj1, PublishScopeListModel* obj2) {

        NSComparisonResult result = [obj1.num compare:obj2.num];
        return result == NSOrderedAscending; // 降序:NSOrderedAscending====升序:NSOrderedDescending
    }];

为UICollectionView添加头视图的两种方式

  • 给UICollectionView添加:UICollectionElementKindSectionHeader
  • 设置UICollectionView的:contentInset
- (UICollectionReusableView*)collectionView:(UICollectionView*)collectionView viewForSupplementaryElementOfKind:(NSString*)kind atIndexPath:(NSIndexPath*)indexPath
{
    UICollectionReusableView* cell = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"_CollectionReusableViewIndetifier" forIndexPath:indexPath];
    return cell;
}
- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section;
{
    return CGSizeMake(ScreenWidth, 44);
}
    CGFloat _adH = 120.0;
    self.collectionView.contentInset = UIEdgeInsetsMake(_adH, 0, 0, 0);
    [self.adImgeView setFrame:CGRectMake(0, CGRectGetMinY(self.collectionView.frame) - _adH, CGRectGetWidth(self.collectionView.frame), _adH)];

TableViewCell创建技巧

#import <UIKit/UIKit.h>
static NSString* SEGPictorialDetailADCellIdentifier = @"SEGPictorialDetailADCellIdentifier";

static NSString* SEGHelpViewCellIdentifier = @"_SEGHelpViewCellIdentifier";  
static NSString* SEGHelpViewCellDetailTopIdentifier = @"_SEGHelpViewCellDetailTopIdentifier";  
static NSString* SEGHelpViewCellDetailDwonIdentifier = @"_SEGHelpViewCellDetailDwonIdentifier";   


@interface SEGPictorialDetailADCell : UITableViewCell
+ (instancetype)cellWithTableView:(UITableView*)tableView;
+ (instancetype)cellWithTableView:(UITableView*)tableView reuseIdentifier:(NSString*)reuseIdentifier;
@end

#import "SEGPictorialDetailADCell.h"

@implementation SEGPictorialDetailADCell

+ (instancetype)cellWithTableView:(UITableView*)tableView
{
    SEGPictorialDetailADCell* cell = [tableView dequeueReusableCellWithIdentifier:SEGPictorialDetailADCellIdentifier];

    if (cell == nil) {

        cell = [[SEGPictorialDetailADCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SEGPictorialDetailADCellIdentifier];
    }


    return cell;
}

+ (instancetype)cellWithTableView:(UITableView*)tableView reuseIdentifier:(NSString*)reuseIdentifier
{
    SEGHelpViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];

    if (cell == nil) {
        cell = [[SEGHelpViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    }

    return cell;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString*)reuseIdentifier
{
    self.CellIdentifier = reuseIdentifier;//通过记录不同的ID来布置对应的界面
    if (self == [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
    }

    return self;
}
@end

TableHeaderView动态改变高度

[self.tableView beginUpdates];
[self.tableView setTableHeaderView:self.webView];
[self.tableView endUpdates];

去掉多余的空白的cell

self.contactsTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

切割图片

UIImage* Image = [UIImage imageNamed:@"RedButton"];
Image = [logBackgroundImage stretchableImageWithLeftCapWidth:logBackgroundImage.size.width * 0.5 topCapHeight:logBackgroundImage.size.height * 0.5];
[self.loginBtn setBackgroundImage:Image forState:UIControlStateNormal];

实现跳转safari,phone或message

//调用 电话phone
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://10086"]];

//调用自带 浏览器 safari
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.baidu.com"]];

//调用 自带mail
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://sam@icloud.com"]];

//调用 SMS
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms://111111"]];

//跳转到系统设置相关界面
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=WIFI"]];

程序中获取软件的版本号和app名称

应用程序的名称和版本号等信息都保存在mainBundle的infoDictionary字典中,用下面代码可以取出来。  
NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];  
NSString* versionNum =[infoDict objectForKey:@"CFBundleVersion"];//版本名称  
NSString*appName =[infoDict objectForKey:@"CFBundleDisplayName"];//app名称 

在有uinavigation,uitoolbar的情况下,如何添加一个全屏的 uiview (作为显示一个进度框,任何区域无法触摸而使用)

[[UIApplication sharedApplication].keyWindow addSubview:waitingview]; 

在项目用代码打开AppStore

NSString *url = [NSString stringWithFormat:@"http://itunes.apple.com/cn/app/huo-xing-she-xin-dian/id549425594?l=en&mt=8"];  
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];

使屏幕一直保持唤醒状态?(就是不自动黑屏)

[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

隐藏UINavigationBar

- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationControllersetNavigationBarHidden:YESanimated:YES]; //设置隐藏
    [super viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [self.navigationControllersetNavigationBarHidden:NOanimated:YES];//设置显示
    [super viewWillDisappear:animated];
}

在navigationviewcontroller中,pop到指定的VC

NSArray *viewControllers=[self.navigationController viewControllers];  
UIViewController *controller=[viewControllers objectAtIndex:1];  //跳转到第一个VC
[self.navigationController popToViewController:controller animated:YES];  

获取手机硬件信息

[[UIDevice currentDevice] systemName];[[UIDevice currentDevice] systemVersion];
[[UIDevice currentDevice] uniqueIdentifier];
[[UIDevice currentDevice] model];
[[UIDevice currentDevice] name];

真机上结果:
System Name: iPhone OSSystem 
Version: 4.2.1
Unique ID: 9b5ded78d5fa0ac96250f8b4af0e46f40b96ea6d
Model: iPhone
Name: “wwk”的 iPhone

模拟器上结果:
System Name: iPhone OSSystem 
Version: 4.2
Unique ID: 21FFE0FF-429B-5D0B-96D2-EADCA3203260
Model: iPhone Simulator
Name: iPhone Simulator

URL编码、解码

// 1. URL编码:ios中http请求遇到汉字的时候,需要转化成UTF-8:
 NSString* urlString = @"http://www.baidu.com!name=小明";
NSString * encodingString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//结果:http://www.baidu.com!name=%E5%B0%8F%E6%98%8E

// 2.URL解码:请求后,返回的数据,如何显示的是这样的格式:%3A%2F%2F,此时需要我们进行UTF-8解码,用到的方法是:
NSString *str = [encodingString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

获取URL中的细节

NSURL* url = [NSURL URLWithString:@"http://www.baidu.com/s?tn=baiduhome_pg&bs=NSRUL&f=8&rsv_bp=1&rsv_spt=1&wd=NSurl&inputT=2709"];
    NSLog(@"Scheme: %@", [url scheme]);
    NSLog(@"Host: %@", [url host]);
    NSLog(@"Port: %@", [url port]);
    NSLog(@"Path: %@", [url path]);
    NSLog(@"Relative path: %@", [url relativePath]);
    NSLog(@"Path components as array: %@", [url pathComponents]);
    NSLog(@"Parameter string: %@", [url parameterString]);
    NSLog(@"Query: %@", [url query]);
    NSLog(@"Fragment: %@", [url fragment]);
    NSLog(@"User: %@", [url user]);
    NSLog(@"Password: %@", [url password]);

/*
2016-05-27 11:38:23.503 FourNews[2358:116708] Scheme: http
2016-05-27 11:38:23.504 FourNews[2358:116708] Host: www.baidu.com
2016-05-27 11:38:23.504 FourNews[2358:116708] Port: (null)
2016-05-27 11:38:23.504 FourNews[2358:116708] Path: /s
2016-05-27 11:38:23.504 FourNews[2358:116708] Relative path: /s
2016-05-27 11:38:23.504 FourNews[2358:116708] Path components as array: (
    "/",
    s
)
2016-05-27 11:38:23.504 FourNews[2358:116708] Parameter string: (null)
2016-05-27 11:38:23.505 FourNews[2358:116708] Query: tn=baiduhome_pg&bs=NSRUL&f=8&rsv_bp=1&rsv_spt=1&wd=NSurl&inputT=2709
2016-05-27 11:38:23.505 FourNews[2358:116708] Fragment: (null)
2016-05-27 11:38:23.505 FourNews[2358:116708] User: (null)
2016-05-27 11:38:23.505 FourNews[2358:116708] Password: (null)
*/

获取URL中的参数

- (NSDictionary*)dictionaryFromQuery:(NSString*)query usingEncoding:(NSStringEncoding)encoding
{
    NSCharacterSet* delimiterSet = [NSCharacterSet characterSetWithCharactersInString:@"&;"];
    NSMutableDictionary* pairs = [NSMutableDictionary dictionary];
    NSScanner* scanner = [[NSScanner alloc] initWithString:query];
    while (![scanner isAtEnd]) {
        NSString* pairString = nil;
        [scanner scanUpToCharactersFromSet:delimiterSet intoString:&pairString];
        [scanner scanCharactersFromSet:delimiterSet intoString:NULL];
        NSArray* kvPair = [pairString componentsSeparatedByString:@"="];
        if (kvPair.count == 2) {
            NSString* key = [[kvPair objectAtIndex:0]
                stringByReplacingPercentEscapesUsingEncoding:encoding];
            NSString* value = [[kvPair objectAtIndex:1]
                stringByReplacingPercentEscapesUsingEncoding:encoding];
            [pairs setObject:value forKey:key];
        }
    }

    return [NSDictionary dictionaryWithDictionary:pairs];
}

[**ViewController respondsToSelector:]: message sent to deallocated instance崩溃问题解决方法

这是因为这个UIViewController释放后,又再次向这个VC调用了某些请求导致的,一般出现这种报错是UIViewController里面有设置xxx.delegate=self,这些代理有延时方法,例如等待网络返回等
当导航栏直接返回时,UIViewController已经被销毁,延时方法再调用此野指针VC,便会导致崩溃
解决方法:
1 在dealloc中设置xx.delegate = nil ,这个是程序没有使用ARC才可以
2 在viewWillDisappear方法中把所有xxx.delegate=self的具有延时方法的delegate置nil,我的做法是不过有没有延时方法,

UIView有关的杂技

//设置View的圆角:
[view.layer setCornerRadius:15.0];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,761评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,953评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,998评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,248评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,130评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,145评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,550评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,236评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,510评论 1 291
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,601评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,376评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,247评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,613评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,911评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,191评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,532评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,739评论 2 335

推荐阅读更多精彩内容

  • 下面的内容基本都是我亲测的 Xcode目录位置:~/Library/Developer/Xcode/ Code S...
    Mr_Zander阅读 328评论 0 1
  • 因为记性不好,常常看到点东西,都感觉很好,但是经常时间一长都忘了,所以现在些杂记,记住这些。慢慢补充。 1.iOS...
    小小看护阅读 122评论 0 0
  • 杂记: 1.安装Xcode插件管理终端命令: curl -fsSL https://raw.githubuserc...
    suncorex阅读 234评论 0 1
  • iOS类库合集: http://www.code4app.com/thread-7831-1-1.htmliOS最...
    暮雨飞烟阅读 140评论 0 0
  • 1,Search Bar 怎样去掉背景的颜色(storyboard里只能设置background颜色,可是发现cl...
    以德扶人阅读 2,289评论 2 50