iOS開發(fā)小技巧

  • [去掉和修改UISearchBar 默認(rèn)的背景色(灰色)和TextField顏色](#去掉和修改UISearchBar 默認(rèn)的背景色(灰色)和TextField顏色)
  • 更改TextField的背景顏色
  • 如何正確的寫TODO,F(xiàn)IXME
    1. 去掉和修改UISearchBar 默認(rèn)的背景色(灰色)和TextField顏色。
      測試環(huán)境:Xcode7, iOS9.2;
      默認(rèn)背景色:


      UISearchBar 默認(rèn)背景色(灰色)
  • 如何取消或修改默認(rèn)的灰色背景呢?一行代碼可以搞定:
// !備注:當(dāng)添加scopeButtons時(shí),以下方法無效
for (UIView *view in self.searchBar.subviews) {
        if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {
            [[view.subviews objectAtIndex:0] removeFromSuperview];
            break;
        }
}
//  添加以下代碼, 將UISearchBar背景顏色更改為藍(lán)色
//  self.searchBar.layer.backgroundColor = [UIColor blueColor].CGColor;  

完成后的效果如下圖:


UISearchBar 去掉背景色后的效果

<a href="changeTextFieldBgColor">更改TextField的背景顏色</a>

//第一種方法,設(shè)置背景圖片, 下面的方法支持iOS5.0
  [self.searchBa setSearchFieldBackgroundImage:[UIImage imageNamed:@"image"]  forState:UIControlStateNormal];

  //第二種方法,獲取SearchBar內(nèi)部的TextField,更改其顏色,不用額外增加圖片
    UITextField *textField = [self.searchBa valueForKey:@"_searchField"];
    textField.backgroundColor = [UIColor clearColor];

<a name="rendering-pane"></a>The Rendering Preference Pane

This is where I keep preferences relating to how I render and style the parsed markdown in the preview window.

3. 取消導(dǎo)航返回鍵的title:

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

4. CocoaPods install CorePlot

測試環(huán)境: Xcode7, Simulator, iPhone6
雖然CorePlot的主頁上沒有顯示如何用CocoaPods安裝CorePlot, 但我們?nèi)匀豢梢杂肅ocoaPods安裝CorePlot

    pod 'CorePlot', '~> 2.0'

在項(xiàng)目中導(dǎo)入CorePlot:

#import <CorePlot/ios/CorePlot.h>

5. 如何統(tǒng)計(jì)項(xiàng)目中代碼的數(shù)量

 在終端中進(jìn)入項(xiàng)目所在文件夾,輸入以下命令即可得到代碼總行數(shù)(包括注釋的代碼哦)
 find . -name "*.m" -or -name "*.h" | xargs grep -v "^$"| wc -l

6. UITabBarController+UINavigaitonController配合使用時(shí),各種情況下,如何設(shè)置tabBarItem.title和navigaitionController的title??? 每次都好煩,這次一次性搞定

  //在TabBarController的實(shí)現(xiàn)文件中實(shí)現(xiàn)以下方法
/**
 **  添加帶有導(dǎo)航控制器的childViewController
 **
 **  @param viewController 將要添加的ViewController, 將為其增加導(dǎo)航控制器
 **  @param show           是否顯示導(dǎo)航控制器頂部的title
 **  @param same           如果show=YES,導(dǎo)航控制器頂部的title是否與tabbarItem的title一致
 **  @param title          導(dǎo)航控制器的title
 **  @param barItemTitle   UITabBarItem的title
 **  @param image          UITabBarItem的image
 **  @param selectedImage  UITabbarItem的selectedImage
 **/
 - (void)addChildViewControlle:(nonnull UIViewController *)viewController showTitle:(BOOL)show same:(BOOL)same title:(nullable NSString *)title barItemTitle:(nonnull NSString *)barItemTitle image:(nonnull UIImage *)image selectedImage:(nonnull UIImage *)selectedImage{
    if (show && (title == nil || [title isEqualToString:@""])) {
        [NSException raise:@"TabBarController set excepition" format:@"The navigaitoncontroller's title cannot be nil because of you choosing show title"];
        return;
    }
    viewController.tabBarItem.image = image;
    viewController.tabBarItem.selectedImage = selectedImage;
    SDRootNavigationController *nav =[[SDRootNavigationController alloc] initWithRootViewController:viewController];
    if (show) {
        if (same) {
            viewController.title = barItemTitle;
        }else{
            viewController.title = title;
            nav.tabBarItem.title = barItemTitle; //如果同時(shí)設(shè)置兩個(gè)title,必須先實(shí)現(xiàn)導(dǎo)航欄的title,再實(shí)現(xiàn)tabbar的title
        }
    }else{
        nav.tabBarItem.title = barItemTitle;
    }
    
    [self addChildViewController:nav];
}
效果圖

7. Xcode目錄自動(dòng)同步

iOS開發(fā)都知道,當(dāng)我們在Xcode中新建一個(gè)Group的時(shí)候,并沒有在finder中建立同步的Directory,當(dāng)我們在finder中查找文件的時(shí)候,確實(shí)是一個(gè)大的麻煩,那么有解決的辦法嗎?答案是YES!
Synx
A command-line tool that reorganizes your Xcode project folder to match your Xcode groups.

Github主頁詳細(xì)介紹了用法,真的很強(qiáng)大。但是在實(shí)際使用過程中可能出現(xiàn)以下的問題:

 //當(dāng)執(zhí)行g(shù)em install synx命令時(shí),可能出現(xiàn)以下的error
ERROR:  While executing gem ... (Gem::FilePermissionError)
You don't have write permissions for the /Library/Ruby/Gems/2.0.0 directory.

http://stackoverflow.com/questions/14607193/installing-gem-or-updating-rubygems-fails-with-permissions-error
我的辦法是使用root權(quán)限

sudo -s  //獲取root權(quán)限
gem install synx //安裝aynx,如果在root權(quán)限下進(jìn)行此命令會(huì)報(bào)錯(cuò)
error : You cannot run Synx as root.
//切換回普通用戶,執(zhí)行同步命令
synx test.xocdeproj
//這樣Xcode目錄就會(huì)和Finder目錄一致了

感謝葉孤城葉大的提點(diǎn)。??

8. ARC下打印對象的引用計(jì)數(shù)

    id obj = [[NSObject alloc]init];
    NSLog(@"retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(obj)));
//output : retain count = 2

9. 如何更改TabBar上面的橫線

  - (UIImage *)contentImageWithColor:(UIColor *)color rect:(CGRect)rect{
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef contenxt = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(contenxt, color.CGColor);
    CGContextFillRect(contenxt, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
//設(shè)置陰影照片,也就是那條橫線,就是那個(gè)高度為0.5的UIImageView
    [self.tabBar setShadowImage:[self contentImageWithColor:RGBCOLOR(247, 248, 247) rect:CGRectMake(0, 0, SCREEN_WIDTH, 0.5)]];
//設(shè)置的時(shí)候,必須同時(shí)設(shè)置bacjgroudImage, 否則無效。
    [self.tabBar setBackgroundImage:[self contentImageWithColor:RGBCOLOR(247, 248, 247) rect:CGRectMake(0, 0, SCREEN_WIDTH, 49)]];

10. Xcode添加代碼塊, 快捷開發(fā), 再也不用重復(fù)的寫Property了

/** <#summary#> */
@property (nonatomic,strong) <#type#> *<#name#>;

真相1

真相2

11. delloc中應(yīng)該寫什么?

(1). 如果當(dāng)前界面有NSTimer, 當(dāng)該界面出棧時(shí),應(yīng)該將定時(shí)器的取消和置空這樣處理

    - (void)viewDidDisappear:(BOOL)animated{
         [super viewDidDisappear:animated];
         [_myTimer invalidate];
          _myTimer = nil;
      }

而不是放在delloc中,否則內(nèi)存得不到釋放
(2). ARC中dealloc中不得顯式調(diào)用[super dealloc]
(3). [NSNotificationCenter defaultCenter] removeObserver 操作應(yīng)該放在delloc中,而不是ViewDisapper中

//官網(wǎng)解釋
The following example illustrates how to unregister someObserver for all notifications for which it had previously registered. This is safe to do in the dealloc method, but should not otherwise be used—use removeObserver:name:object: instead.

12. 如何獲取APP的名稱?

//獲取appName-info.plist中app的名稱(適用于只有一個(gè)名字的情況)
[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]
//獲取InfoPlist.strings中的app名稱(適用于有中英文或者多個(gè)Target的情況)
[[[NSBundle mainBundle] localizedInfoDictionary] objectForKey:@"CFBundleDisplayName"]

13. Mac顯示和隱藏文件夾

在終端(Terminal)輸入如下命令,即可顯示隱藏文件和文件夾

defaults write com.apple.finder AppleShowAllFiles -boolean true ; killall Finder

如需再次隱藏原本隱藏的文件和文件夾,可以輸入如下命令

defaults write com.apple.finder AppleShowAllFiles -boolean false ; killall Finder

14. 消除‘performSelector may cause a leak because its selector is unkonwn'

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
      [self performSelector:selector withObject:info];
#pragma clang diagnostic pop

15: 獲取設(shè)備內(nèi)所有已安裝APP的信息(訪問私有方法,上架可能被拒)

    Class c =NSClassFromString(@"LSApplicationWorkspace");
    id s = [(id)c performSelector:NSSelectorFromString(@"defaultWorkspace")];
    NSArray *array = [s performSelector:NSSelectorFromString(@"allInstalledApplications")];
    for (id item in array){
        NSLog(@"%@",[item performSelector:NSSelectorFromString(@"applicationIdentifier")]);
        //NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleIdentifier")]);
        NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleVersion")]);
        NSLog(@"%@",[item performSelector:NSSelectorFromString(@"shortVersionString")]);
    }
    

16:獲取系統(tǒng)版本號(hào)的正確方式

   [NSProcessInfo processInfo].operatingSystemVersion
    NSInteger major = [NSProcessInfo processInfo].operatingSystemVersion.majorVersion;
    NSInteger minor = [NSProcessInfo processInfo].operatingSystemVersion.minorVersion;
    NSInteger patch = [NSProcessInfo processInfo].operatingSystemVersion.patchVersion;

17:一個(gè)全局的數(shù)組

static NSString const *presendientOfUsa[4] = {
    @"Obama",
    @"Trump",
    @"Bush",
    @"Washington"
};
static NSString const *imgArr[3] = {
    @"引導(dǎo)頁1",
    @"引導(dǎo)頁2",
    @"引導(dǎo)頁3"
};
除了NSString類型之外,都不允許在方法外部聲明一個(gè)‘靜態(tài)全局常量類型的OC對象’。
你聲明的static const NSArray * presendientOfUsa 在‘編譯’的時(shí)候系統(tǒng)并不知道imgArr是什么類型,PS:全局常量類型的常量,static const是系統(tǒng)在編譯的時(shí)候就需要確定你所定義的常量是什么類型的,然而OC的對象的類型是在‘運(yùn)行時(shí)’確定的。與基本數(shù)據(jù)類型的確定時(shí)間不同,由編譯的時(shí)候推到了運(yùn)行時(shí)(OC支持多態(tài)的原因)。
但是NSString除外,NSString是一種特殊的數(shù)據(jù)類型,有特殊的存儲(chǔ)結(jié)構(gòu)和權(quán)限來保證系統(tǒng)能夠識(shí)別。

18: 如何正確的寫TODO,F(xiàn)IXME

開發(fā)中有一些工作是需要我們稍后完成的,我們用TODO標(biāo)記;有一些暫時(shí)處理不了的bug,用FIXME標(biāo)記,后續(xù)處理,一般是這樣


TODO,F(xiàn)IXME

有一個(gè)潛在的問題是:如果我們忘了?或者同事不知道這些標(biāo)記,可能會(huì)出現(xiàn)遺留問題。我們希望在程序運(yùn)行的時(shí)候,能夠清除的看到,一般在Issue navigator上。
那我們增加一個(gè)腳本,在程序運(yùn)行時(shí),自動(dòng)檢測出這些信息,并增加在Issue navigator上

TAGS="TODO:|FIXME:"
echo "searching ${SRCROOT} for ${TAGS}"
find "${SRCROOT}" \( -name "*.m" \) -print0 | xargs -0 egrep --with-filename --line-number --only-matching "($TAGS).*\$" | perl -p -e "s/($TAGS)/ warning: \$1/"
添加過程
運(yùn)行后的效果

19: Weak and Strong

#define WeakSelf(type) __weak typeof(type) weak##type = type; //weak
#define StrongSelf(type) __strong typeof(type) type = weak##type; //strong

20: UIScrollView(UITableVIew and UICollectionView) 滑動(dòng)到頂部

 ??   [self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
 ?   [self.tableView setContentOffset:CGPointZero animated:YES];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容