当前位置: 移动技术网 > 移动技术>移动开发>IOS > iOS开发零碎知识点

iOS开发零碎知识点

2018年09月17日  | 移动技术网移动技术  | 我要评论

ios开发零碎知识点。记录一些常用和不常用的ios知识点,防止遗忘丢失。

一、调用代码使app进入后台,达到点击home键的效果。(私有api)

    [[uiapplication sharedapplication] performselector:@selector(suspend)];

suspend的英文意思有:暂停; 悬; 挂; 延缓;

二、带有中文的url处理。(非utf-8处理,注意一下)

大概举个例子,类似下面的url,里面直接含有中文,可能导致播放不了,那么我们要处理一个这个url,因为他太操蛋了,居然用中文。

http://static.tripbe.com/videofiles/视频/我的自拍视频.mp4
nsstring *path  = (__bridge_transfer nsstring *)cfurlcreatestringbyreplacingpercentescapesusingencoding(null,                                                                                                             (__bridge cfstringref)model.mp4_url,                                                                                                        cfstr(""),                                                                                                                cfstringconvertnsstringencodingtoencoding(nsutf8stringencoding));

三、获取uiwebview的高度
个人最常用的获取方法,感觉这个比较靠谱

- (void)webviewdidfinishload:(uiwebview *)webview  {  
    cgfloat height = [[webview stringbyevaluatingjavascriptfromstring:@"document.body.offsetheight"] floatvalue];  
    cgrect frame = webview.frame;  
    webview.frame = cgrectmake(frame.origin.x, frame.origin.y, frame.size.width, height);  
}  

四、给uiview设置图片(uilabel一样适用)

第一种方法:
利用的uiview的设置背景颜色方法,用图片做图案颜色,然后传给背景颜色。

uicolor *bgcolor = [uicolor colorwithpatternimage: [uiimage imagenamed:@"bgimg.png"];
        uiview *myview = [[uiview alloc] initwithframe:cgrectmake(0,0,320,480)];
[myview setbackgroundcolor:bgcolor];

第二种方法:

uiimage *image = [uiimage imagenamed:@"yourpicname@2x.png"];
yourview.layer.contents = (__bridge id)image.cgimage;
//设置显示的图片范围
yourview.layer.contentscenter = cgrectmake(0.25,0.25,0.5,0.5);//四个值在0-1之间,对应的为x,y,width,height。

五、去掉uitableview多余的分割线

yourtableview.tablefooterview = [uiview new];

六、调整cell分割线的位置,两个方法一起用,暴力解决,防脱发

-(void)viewdidlayoutsubviews {

    if ([self.mytableview respondstoselector:@selector(setseparatorinset:)]) {
        [self.mytableview setseparatorinset:uiedgeinsetsmake(0, 0, 0, 0)];

    }
    if ([self.mytableview respondstoselector:@selector(setlayoutmargins:)])  {
        [self.mytableview setlayoutmargins:uiedgeinsetsmake(0, 0, 0, 0)];
    }

}

#pragma mark - cell分割线
- (void)tableview:(uitableview *)tableview willdisplaycell:(uitableviewcell *)cell forrowatindexpath:(nsindexpath *)indexpath
{
    if ([cell respondstoselector:@selector(setseparatorinset:)]){
        [cell setseparatorinset:uiedgeinsetsmake(0, 0, 0, 0)];
    }
    if ([cell respondstoselector:@selector(setlayoutmargins:)]) {
        [cell setlayoutmargins:uiedgeinsetsmake(0, 0, 0, 0)];
    }
}

七、uilabel和uiimageview的交互userinteractioneabled默认为no。那么如果你把这两个类做为父试图的话,里面的所有东东都不可以点击哦。曾经有一个人,让我帮忙调试bug,他调试很久没搞定,就是把wmplayer对象(播放器对象)放到一个uiimageview上面。这样imageview addsubview:wmplayer 后,播放器的任何东东都不能点击了。userinteractioneabled设置为yes即可。

八、uisearchcontroller和uisearchbar的cancle按钮改title问题,简单粗暴

- (bool)searchbarshouldbeginediting:(uisearchbar *)searchbar
{
    searchcontroller.searchbar.showscancelbutton = yes;
    uibutton *cancelbtn = [searchcontroller.searchbar valueforkey:@"cancelbutton"];
    [cancelbtn settitle:@"取消" forstate:uicontrolstatenormal];
    [cancelbtn settitlecolor:[uicolor colorwithred:14.0/255.0 green:180.0/255.0 blue:0.0/255.0 alpha:1.00] forstate:uicontrolstatenormal];
    searchbar.showscancelbutton = yes;
    return yes;
}

九、uitableview收起键盘何必这么麻烦
一个属性搞定,效果好(uiscrollview同样可以使用)
以前是不是觉得[self.view endediting:yes];很屌,这个下面的更屌。
yourtableview.keyboarddismissmode = uiscrollviewkeyboarddismissmodeondrag;

另外一个枚举为uiscrollviewkeyboarddismissmodeinteractive,表示在键盘内部滑动,键盘逐渐下去。

十、nstimer
1、nstimer计算的时间并不精确
2、nstimer需要添加到runloop运行才会执行,但是这个runloop的线程必须是已经开启。
3、nstimer会对它的tagert进行retain,我们必须对其重复性的使用intvailte停止。target如果是self(指uiviewcontroller),那么vc的retaincount+1,如果你不释放nstimer,那么你的vc就不会dealloc了,内存泄漏了。

十一、uiviewcontroller没用大小(frame)
经常有人在群里问:怎么改变vc的大小啊?
瞬间无语。(只有uiview才能设置大小,vc是控制器啊,哥!)

十二、用十六进制获取uicolor(类方法或者category都可以,这里我用工具类方法)

+ (uicolor *)colorwithhexstring:(nsstring *)color
{
    nsstring *cstring = [[color stringbytrimmingcharactersinset:[nscharacterset whitespaceandnewlinecharacterset]] uppercasestring];

    // string should be 6 or 8 characters
    if ([cstring length] < 6) {
        return [uicolor clearcolor];
    }

    // strip 0x if it appears
    if ([cstring hasprefix:@"0x"])
        cstring = [cstring substringfromindex:2];
    if ([cstring hasprefix:@"#"])
        cstring = [cstring substringfromindex:1];
    if ([cstring length] != 6)
        return [uicolor clearcolor];

    // separate into r, g, b substrings
    nsrange range;
    range.location = 0;
    range.length = 2;

    //r
    nsstring *rstring = [cstring substringwithrange:range];

    //g
    range.location = 2;
    nsstring *gstring = [cstring substringwithrange:range];

    //b
    range.location = 4;
    nsstring *bstring = [cstring substringwithrange:range];

    // scan values
    unsigned int r, g, b;
    [[nsscanner scannerwithstring:rstring] scanhexint:&r];
    [[nsscanner scannerwithstring:gstring] scanhexint:&g];
    [[nsscanner scannerwithstring:bstring] scanhexint:&b];

    return [uicolor colorwithred:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

十三、获取今天是星期几

+ (nsstring *) getweekdaystringwithdate:(nsdate *) date
{
    nscalendar * calendar = [[nscalendar alloc] initwithcalendaridentifier:nsgregoriancalendar]; // 指定日历的算法
    nsdatecomponents *comps = [calendar components:nsweekdaycalendarunit fromdate:date];

    // 1 是周日,2是周一 3.以此类推

    nsnumber * weeknumber = @([comps weekday]);
    nsinteger weekint = [weeknumber integervalue];
    nsstring *weekdaystring = @"(周一)";
    switch (weekint) {
        case 1:
        {
            weekdaystring = @"(周日)";
        }
            break;

        case 2:
        {
            weekdaystring = @"(周一)";
        }
            break;

        case 3:
        {
            weekdaystring = @"(周二)";
        }
            break;

        case 4:
        {
            weekdaystring = @"(周三)";
        }
            break;

        case 5:
        {
            weekdaystring = @"(周四)";
        }
            break;

        case 6:
        {
            weekdaystring = @"(周五)";
        }
            break;

        case 7:
        {
            weekdaystring = @"(周六)";
        }
            break;

        default:
            break;
    }
    return weekdaystring;

}

十四、uiview的部分圆角问题

uiview *view2 = [[uiview alloc] initwithframe:cgrectmake(120, 10, 80, 80)];
view2.backgroundcolor = [uicolor redcolor];
[self.view addsubview:view2];

uibezierpath *maskpath = [uibezierpath bezierpathwithroundedrect:view2.bounds byroundingcorners:uirectcornerbottomleft | uirectcornerbottomright cornerradii:cgsizemake(10, 10)];
cashapelayer *masklayer = [[cashapelayer alloc] init];
masklayer.frame = view2.bounds;
masklayer.path = maskpath.cgpath;
view2.layer.mask = masklayer;
//其中,
byroundingcorners:uirectcornerbottomleft | uirectcornerbottomright
//指定了需要成为圆角的角。该参数是uirectcorner类型的,可选的值有:
* uirectcornertopleft
* uirectcornertopright
* uirectcornerbottomleft
* uirectcornerbottomright
* uirectcornerallcorners

从名字很容易看出来代表的意思,使用“|”来组合就好了。

十五、设置滑动的时候隐藏navigationbar

navigationcontroller.hidesbarsonswipe = yes;

十六、ios画虚线
记得先 quartzcore框架的导入

#import 

cgcontextref context =uigraphicsgetcurrentcontext();  
cgcontextbeginpath(context);  
cgcontextsetlinewidth(context, 2.0);  
cgcontextsetstrokecolorwithcolor(context, [uicolor whitecolor].cgcolor);  
cgfloat lengths[] = {10,10};  
cgcontextsetlinedash(context, 0, lengths,2);  
cgcontextmovetopoint(context, 10.0, 20.0);  
cgcontextaddlinetopoint(context, 310.0,20.0);  
cgcontextstrokepath(context);  
cgcontextclosepath(context);  

十七、自动布局中多行uilabel,需要设置其preferredmaxlayoutwidth属性才能正常显示多行内容。另外如果出现显示不全文本,可以在计算的结果基础上+0.5。

    cgfloat h = [model.message boundingrectwithsize:cgsizemake([uiscreen mainscreen].bounds.size.width - kgap-kavatar_size - 2*kgap, cgfloat_max) options:nsstringdrawinguseslinefragmentorigin attributes:attributes context:nil].size.height+0.5;

十八、 禁止程序运行时自动锁屏
[[uiapplication sharedapplication] setidletimerdisabled:yes];

十九、kvc相关,支持操作符
kvc同时还提供了很复杂的函数,主要有下面这些
①简单集合运算符
简单集合运算符共有@avg, @count , @max , @min ,@sum5种,都表示啥不用我说了吧, 目前还不支持自定义。

@interface book : nsobject
@property (nonatomic,copy)  nsstring* name;
@property (nonatomic,assign)  cgfloat price;
@end
@implementation book
@end


book *book1 = [book new];
book1.name = @"the great gastby";
book1.price = 22;
book *book2 = [book new];
book2.name = @"time history";
book2.price = 12;
book *book3 = [book new];
book3.name = @"wrong hole";
book3.price = 111;

book *book4 = [book new];
book4.name = @"wrong hole";
book4.price = 111;

nsarray* arrbooks = @[book1,book2,book3,book4];
nsnumber* sum = [arrbooks valueforkeypath:@"@sum.price"];
nslog(@"sum:%f",sum.floatvalue);
nsnumber* avg = [arrbooks valueforkeypath:@"@avg.price"];
nslog(@"avg:%f",avg.floatvalue);
nsnumber* count = [arrbooks valueforkeypath:@"@count"];
nslog(@"count:%f",count.floatvalue);
nsnumber* min = [arrbooks valueforkeypath:@"@min.price"];
nslog(@"min:%f",min.floatvalue);
nsnumber* max = [arrbooks valueforkeypath:@"@max.price"];
nslog(@"max:%f",max.floatvalue);

打印结果
2016-04-20 16:45:54.696 kvcdemo[1484:127089] sum:256.000000
2016-04-20 16:45:54.697 kvcdemo[1484:127089] avg:64.000000
2016-04-20 16:45:54.697 kvcdemo[1484:127089] count:4.000000
2016-04-20 16:45:54.697 kvcdemo[1484:127089] min:12.000000

nsarray 快速求总和 最大值 最小值 和 平均值

nsarray *array = [nsarray arraywithobjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];
cgfloat sum = [[array valueforkeypath:@"@sum.floatvalue"] floatvalue];
cgfloat avg = [[array valueforkeypath:@"@avg.floatvalue"] floatvalue];
cgfloat max =[[array valueforkeypath:@"@max.floatvalue"] floatvalue];
cgfloat min =[[array valueforkeypath:@"@min.floatvalue"] floatvalue];
nslog(@"%f\n%f\n%f\n%f",sum,avg,max,min);

二十、使用mbprogresshud时,尽量不要加到uiwindow上,加self.view上即可。如果加uiwindow上在ipad上,旋转屏幕的时候mbprogresshud不会旋转。之前有人遇到这个bug,我让他改放到self.view上即可解决此bug。

二十一、强制让app直接退出(非闪退,非崩溃)

    - (void)exitapplication {
        appdelegate *app = [uiapplication sharedapplication].delegate;
        uiwindow *window = app.window;
        [uiview animatewithduration:1.0f animations:^{
            window.alpha = 0;
        } completion:^(bool finished) {
            exit(0);
        }];
    }

二十二、label行间距

 nsmutableattributedstring *attributedstring =    
   [[nsmutableattributedstring alloc] initwithstring:self.contentlabel.text];
    nsmutableparagraphstyle *paragraphstyle =  [[nsmutableparagraphstyle alloc] init];  
   [paragraphstyle setlinespacing:3];

    //调整行间距       
   [attributedstring addattribute:nsparagraphstyleattributename 
                         value:paragraphstyle 
                         range:nsmakerange(0, [self.contentlabel.text length])];
     self.contentlabel.attributedtext = attributedstring;

二十三、cocoapods pod install/pod update更新慢的问题
pod install –verbose –no-repo-update
pod update –verbose –no-repo-update
如果不加后面的参数,默认会升级cocoapods的spec仓库,加一个参数可以省略这一步,然后速度就会提升不少。

二十四、mrc和arc混编设置方式
在xcode中targets的build phases选项下compile sources下选择 不需要arc编译的文件
双击输入 -fno-objc-arc 即可
mrc工程中也可以使用arc的类,方法如下:
在xcode中targets的build phases选项下compile sources下选择要使用arc编译的文件
双击输入 -fobjc-arc 即可

二十五、把tableview里cell的小对勾的颜色改成别的颜色
_yourtableview.tintcolor = [uicolor redcolor];

二十六、解决同时按两个按钮进两个view的问题
[button setexclusivetouch:yes];

二十七、修改textfieldplaceholder字体颜色和大小

textfield.placeholder = @"请输入用户名";  
[textfield setvalue:[uicolor redcolor] forkeypath:@"_placeholderlabel.textcolor"];  
[textfield setvalue:[uifont boldsystemfontofsize:16] forkeypath:@"_placeholderlabel.font"];

二十八、禁止textfield和textview的复制粘贴菜单

-(bool)canperformaction:(sel)action withsender:(id)sender
{
     if ([uimenucontroller sharedmenucontroller]) {
       [uimenucontroller sharedmenucontroller].menuvisible = no;
     }
     return no;
}

二十九:如何进入我的软件在app store 的页面
先用itunes link maker找到软件在访问地址,格式为itms-apps://ax.itunes.apple.com/…,然后

#define  ituneslink   @"itms-apps://ax.itunes.apple.com/..."
nsurl *url = [nsurl urlwithstring:ituneslink];
if([[uiapplication sharedapplication] canopenurl:url]){
     [[uiapplication sharedapplication] openurl:url];
}

如果把上述地址中itms-apps改为http就可以在中打开了。可以把这个地址放在自己的网站里,链接到app store。
itunes link maker地址:

三十、二级三级页面隐藏tabbar
1、单个处理

yourviewcontroller *yourvc = [yourviewcontroller new];
yourvc.hidesbottombarwhenpushed = yes;
[self.navigationcontroller pushviewcontroller:yourvc animated:yes];

2.统一在基类里面处理
新建一个类basenavigationcontroller继承uinavigationcontroller,然后重写 -(void)pushviewcontroller:(uiviewcontroller *)viewcontroller animated:(bool)animated这个方法。所有的push事件都走此方法。

@interface basenavigationcontroller : uinavigationcontroller

@end
    -(void)pushviewcontroller:(uiviewcontroller *)viewcontroller animated:(bool)animated{
        [super pushviewcontroller:viewcontroller animated:animated];
        if (self.viewcontrollers.count>1) {
            viewcontroller.hidesbottombarwhenpushed = yes;
        }
    }

三十一、取消系统的返回手势

   self.navigationcontroller.interactivepopgesturerecognizer.enabled = no;

三十二、修改uiwebview中字体的大小,颜色

1、uiwebview设置字体大小,颜色,字体:
uiwebview无法通过自身的属性设置字体的一些属性,只能通过html代码进行设置
在webview加载完毕后,在

- (void)webviewdidfinishload:(uiwebview *)webview方法中加入js代码  
    nsstring *str = @"document.getelementsbytagname('body')[0].style.webkittextsizeadjust= '60%'";  
    [_webview stringbyevaluatingjavascriptfromstring:str]; 

或者加入以下代码

nsstring *jsstring = [[nsstring alloc] initwithformat:@"document.body.style.fontsize=%f;document.body.style.color=%@",fontsize,fontcolor];   
        [webview stringbyevaluatingjavascriptfromstring:jsstring];   

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网