1. 移除控件上所有得子控件
方法一:
[view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
方法二:
- (void)removeAllSubviews {
//[self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
while (self.subviews.count) {
[self.subviews.lastObject removeFromSuperview];
}
}
方法三:
[xxxView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[obj removeFromSuperview];
}];
2. 直接滾動到Scrollview的底部
- (void)scrollsToBottomAnimated:(BOOL)animated
{
CGFloat offset = self.tableView.contentSize.height - self.tableView.bounds.size.height;
if (offset > 0)
{
[self.tableView setContentOffset:CGPointMake(0, offset) animated:animated];
}
}
3. 給Label文字添加行距和文字距離+計算其高度
#define UILABEL_LINE_SPACE 6
#define HEIGHT [ [ UIScreen mainScreen ] bounds ].size.height
//給UILabel設(shè)置行間距和字間距
-(void)setLabelSpace:(UILabel*)label withValue:(NSString*)str withFont:(UIFont*)font {
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStylealloc] init];
paraStyle.lineBreakMode =NSLineBreakByCharWrapping;
paraStyle.alignment =NSTextAlignmentLeft;
paraStyle.lineSpacing = UILABEL_LINE_SPACE; //設(shè)置行間距
paraStyle.hyphenationFactor = 1.0;
paraStyle.firstLineHeadIndent =0.0;
paraStyle.paragraphSpacingBefore =0.0;
paraStyle.headIndent = 0;
paraStyle.tailIndent = 0;
//設(shè)置字間距 NSKernAttributeName:@1.5f
NSDictionary *dic =@{NSFontAttributeName:font,NSParagraphStyleAttributeName:paraStyle,NSKernAttributeName:@1.5f
};
NSAttributedString *attributeStr = [[NSAttributedStringalloc] initWithString:strattributes:dic];
label.attributedText = attributeStr;
}
//計算UILabel的高度(帶有行間距的情況)
-(CGFloat)getSpaceLabelHeight:(NSString*)str withFont:(UIFont*)font withWidth:(CGFloat)width {
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStylealloc] init];
paraStyle.lineBreakMode =NSLineBreakByCharWrapping;
paraStyle.alignment =NSTextAlignmentLeft;
paraStyle.lineSpacing = UILABEL_LINE_SPACE;
paraStyle.hyphenationFactor = 1.0;
paraStyle.firstLineHeadIndent =0.0;
paraStyle.paragraphSpacingBefore =0.0;
paraStyle.headIndent = 0;
paraStyle.tailIndent = 0;
NSDictionary *dic =@{NSFontAttributeName:font,NSParagraphStyleAttributeName:paraStyle,NSKernAttributeName:@1.5f
};
CGSize size = [strboundingRectWithSize:CGSizeMake(width,HEIGHT) options:NSStringDrawingUsesLineFragmentOriginattributes:dic context:nil].size;
return size.height;
}
4. 使用Masonry后结洼、使frame及時生效(需要在mas_makeConstraints之后用它的父視圖調(diào)用layoutIfNeeded可以使得約束立即生效
)
UIView *view = [UIView new];
[self.view addSubview:view];
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(10, 10, 10, 10));
}];
view.backgroundColor = [UIColor redColor];
[self.view layoutIfNeeded];
NSLog(@"%@",view1.description);
5. 自定義View的淡入淡出
// 淡入
- (void)fadeIn
{
self.transform = CGAffineTransformMakeScale(1.3, 1.3);
self.alpha = 0;
[UIView animateWithDuration:.35 animations:^{
self.alpha = 1;
self.transform = CGAffineTransformMakeScale(1, 1);
}];
}
// 淡出
- (void)fadeOut
{
[UIView animateWithDuration:.35 animations:^{
self.transform = CGAffineTransformMakeScale(1.3, 1.3);
self.alpha = 0.0;
} completion:^(BOOL finished) {
if (finished) {
[self removeFromSuperview];
}
}];
}
// 向上彈起
- (void)show{
UIWindow *currentWindows = [UIApplication sharedApplication].keyWindow;
self.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.2];
[currentWindows addSubview:self];
[UIView animateWithDuration:.3 animations:^{
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
self.backView.frame = ScreenBounds;
}];
}
// 向下彈出
- (void)dissMissView{
[UIView animateWithDuration:.3 animations:^{
[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
self.backView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, ScreenHeight);
} completion:^(BOOL finished) {
[self removeFromSuperview];
}];
}
6. 圖片拉伸方法(- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode
)的使用
/**
參數(shù)一:capInsets是UIEdgeInsets類型的數(shù)據(jù),即原始圖像要被保護的區(qū)域
參數(shù)二:resizingMode是UIImageResizingMode類似的數(shù)據(jù),即圖像拉伸時選用的拉伸模式
UIImageResizingModeTile, 平鋪
UIImageResizingModeStretch, 拉伸
*/
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode
7. iOS中超出父視圖的按鈕點擊事件響應(yīng)處理(方法一有問題
)
方法一:
//在父控件里面重寫此方法、self.launchBtn為當(dāng)前控件
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
UIView * view = [super hitTest:point withEvent:event];
if (view == nil) {
// 轉(zhuǎn)換坐標系
CGPoint newPoint = [self.launchBtn convertPoint:point fromView:self];
// 判斷觸摸點是否在button上
if (CGRectContainsPoint(self.launchBtn.bounds, newPoint)) {
view = self.launchBtn;
}
}
return view;
}
方法二:
//重寫hitTest方法,去監(jiān)聽發(fā)布按鈕的點擊助琐,目的是為了讓凸出的部分點擊也有反應(yīng)
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
//這一個判斷是關(guān)鍵,不判斷的話push到其他頁面,點擊發(fā)布按鈕的位置也是會有反應(yīng)的疟暖,這樣就不好了
//self.isHidden == NO 說明當(dāng)前頁面是有tabbar的,那么肯定是在導(dǎo)航控制器的根控制器頁面
//在導(dǎo)航控制器根控制器頁面田柔,那么我們就需要判斷手指點擊的位置是否在發(fā)布按鈕身上
//是的話讓發(fā)布按鈕自己處理點擊事件俐巴,不是的話讓系統(tǒng)去處理點擊事件就可以了
if (self.isHidden == NO) {
//將當(dāng)前tabbar的觸摸點轉(zhuǎn)換坐標系,轉(zhuǎn)換到發(fā)布按鈕的身上硬爆,生成一個新的點
CGPoint newP = [self convertPoint:point toView:self.publishButton];
//判斷如果這個新的點是在發(fā)布按鈕身上欣舵,那么處理點擊事件最合適的view就是發(fā)布按鈕
if ( [self.publishButton pointInside:newP withEvent:event]) {
return self.publishButton;
}else{//如果點不在發(fā)布按鈕身上,直接讓系統(tǒng)處理就可以了
return [super hitTest:point withEvent:event];
}
}
else {//tabbar隱藏了缀磕,那么說明已經(jīng)push到其他的頁面了缘圈,這個時候還是讓系統(tǒng)去判斷最合適的view處理就好了
return [super hitTest:point withEvent:event];
}
}
8. 獲得Xcode里面所有字體的字體樣式
// 獲取字體樣式
NSArray *familyNames = [UIFont familyNames];
for( NSString *familyName in familyNames )
{
NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
for( NSString *fontName in fontNames )
{
printf( "\tFont: %s \n", [fontName UTF8String] );
}
}
// 使用字體
self.label.text = @"login";
self.label.font = [UIFont fontWithName:@"Century-GothicT." size:30];
9. Xcode里面中文文字設(shè)置斜體
// ios中不支持中文傾斜,于是只有設(shè)置傾斜角度袜蚕。
// 第一行代碼:設(shè)置反射糟把。傾斜15度。
CGAffineTransform matrix = CGAffineTransformMake(1,0,tanf(15*(CGFloat)M_PI/180),1,0,0);
// 第二行代碼:取得系統(tǒng)字符并設(shè)置反射牲剃。
UIFontDescriptor *desc = [ UIFontDescriptor fontDescriptorWithName:[UIFont systemFontOfSize :17 ]. fontName matrix :matrix];
// 第三行代碼:獲取字體遣疯。
UIFont *font = [UIFont fontWithDescriptor:desc size :17];
10. + initialize 與 +load調(diào)用時機
load 方法會在加載類的時候就被調(diào)用,也就是 ios 應(yīng)用啟動的時候凿傅,就會加載所有的類缠犀,就會調(diào)用每個類的 + load 方法。
initialize 方法類似一個懶加載聪舒,如果沒有使用這個類辨液,那么系統(tǒng)默認不會去調(diào)用這個方法,且默認只加載一次箱残; initialize 的調(diào)用發(fā)生在 +init 方法之前滔迈。
11. 更改webViewl里面html的字體樣式
NSString* htmlPath = [[NSBundle mainBundle] pathForResource:@"enLATP" ofType:@"html"];
NSString* appHtml = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
UIFont *font = [UIFont fontWithScaledSize:14];
UIFont *font1 = [UIFont fontWithBigSize:16];
NSString *fontColor = @"CCCCFF";
NSString *fontColor1 = @"000000";
NSString *htmlString =[NSString stringWithFormat:@"<html> \n"
"<head> \n"
"<style type=\"text/css\"> \n"
"body {font-family: \"%@\"; color: %@;}\n"
".boldFont {font-family: \"%@\"; color: %@;}\n"
"</style> \n"
"</head> \n"
"<body>%@</body> \n"
"</html>", font.familyName,fontColor,font1.familyName,fontColor1,appHtml];
if(htmlPath.length==0)
{
return;
}
NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
[self.webView loadHTMLString:htmlString baseURL:baseURL];
12. 點擊屏幕鍵盤退出
- (void)sp_addReturnKeyBoard {
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
tap.numberOfTapsRequired = 1;
tap.numberOfTouchesRequired = 1;
[tap.rac_gestureSignal subscribeNext:^(id x) {
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate.window endEditing:YES];
}];
[self addGestureRecognizer:tap];
}
13. 通知標準寫法(建議使用)
// Foo.h
UIKIT_EXTERN NSNotificationName const ZOCFooDidBecomeBarNotification
// Foo.m
NSNotificationName const ZOCFooDidBecomeBarNotification = @"ZOCFooDidBecomeBarNotification";
14. 獲取APP當(dāng)前所在的ViewController
- (UIViewController *)findBestViewController:(UIViewController*)vc {
if (vc.presentedViewController) {
// Return presented view controller
return [self findBestViewController:vc.presentedViewController];
} else if ([vc isKindOfClass:[UISplitViewController class]]) {
// Return right hand side
UISplitViewController* svc = (UISplitViewController*) vc;
if (svc.viewControllers.count > 0)
return [self findBestViewController:svc.viewControllers.lastObject];
else
return vc;
} else if ([vc isKindOfClass:[UINavigationController class]]) {
// Return top view
UINavigationController* svc = (UINavigationController*) vc;
if (svc.viewControllers.count > 0)
return [self findBestViewController:svc.topViewController];
else
return vc;
} else if ([vc isKindOfClass:[UITabBarController class]]) {
// Return visible view
UITabBarController* svc = (UITabBarController*) vc;
if (svc.viewControllers.count > 0)
return [self findBestViewController:svc.selectedViewController];
else
return vc;
} else {
// Unknown view controller type, return last child view controller
return vc;
}
}
- (UIViewController*) currentViewController {
// Find best view controller
UIViewController* viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
return [self findBestViewController:viewController];
}
調(diào)用
UIViewController * viewControllerNow = [self currentViewController];
if ([viewControllerNow isKindOfClass:[PCBConversationController class]]) { //如果是頁面XXX,則執(zhí)行下面語句
item.badgeValue = nil;
}else{}
15. 通知的注冊和移除
-(void) viewWillAppear:(BOOL)animated 方法里面注冊
-(void) viewWillDisappear:(BOOL)animated;方法里面移除
16.判斷當(dāng)前頁面是Push過來還是present過來
方法一:
通過判斷self有沒有present方式顯示的父視圖presentingViewController
if (self.presentingViewController) {
[self dismissViewControllerAnimated:YES completion:nil];
} else {
[self.navigationController popViewControllerAnimated:YES];
}
方法二:(若果present的ControllView的帶有UINavigationBar不能使用此方法)
通過判斷self有沒有present方式顯示的父視圖
if (self.navigationController.topViewController == self) {
[self.navigationController popViewControllerAnimated:YES];
} else {
[self dismissViewControllerAnimated:YES completion:nil];
}
17. CollectioView滾動到指定section的方法
https://www.cnblogs.com/tinych/p/5891665.html
18.查看自己編寫的代碼行數(shù)
1. cd到代碼的文件夾下面
2. 然后編輯一下命令
find . "(" -name "*.m" -or -name "*.mm" -or -name "*.cpp" -or -name "*.h" -or -name "*.rss" ")" -print | xargs wc -l
19.新特性頁面漸隱跳轉(zhuǎn)到主頁面
#pragma mark - 使頁面動態(tài)消失
- (void)restoreRootViewController:(UIViewController *)rootViewController {
[UIView transitionWithView:[UIApplication sharedApplication].keyWindow duration:0.5f options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
BOOL oldState = [UIView areAnimationsEnabled];
[UIView setAnimationsEnabled:NO];
[UIApplication sharedApplication].keyWindow.rootViewController = rootViewController;
[UIView setAnimationsEnabled:oldState];
} completion:nil];
}
使用方法
// 設(shè)置跟控制器
PCBLoginController *loginVc = [[PCBLoginController alloc]init];
CTNavigationController *naVc = [[CTNavigationController alloc]initWithRootViewController:loginVc];
// 切換控制器
[self restoreRootViewController:naVc];
使用CATransition方法達到此效果
// 跳轉(zhuǎn)到核心界面,push,modal,切換跟控制器的方法
KeyWindow.rootViewController = [[TabBarController alloc] init];
CATransition *anim = [CATransition animation];
anim.duration = 0.5;
anim.type = @"rippleffect";
[KeyWindow.layer addAnimation:anim forKey:nil];
20.貨幣價格計算,使用float類型運算亡鼠,經(jīng)常出現(xiàn)誤差赏殃。
在iOS開發(fā)中,經(jīng)常遇到和貨幣價格計算相關(guān)的间涵,這時就需要注意計算精度的問題仁热。使用float類型運算,經(jīng)常出現(xiàn)誤差勾哩。為了解決這種問題我們使用NSDecimalNumber抗蠢,下面將通過例子的形式給大家展示一下。
點擊查看
21.解決APP切入到后臺思劳,倒計時停止的問題
- (void)applicationDidEnterBackground:(UIApplication *)application {
UIApplication *app = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier bgTask;
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid){
bgTask = UIBackgroundTaskInvalid;
}
});
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid){
bgTask = UIBackgroundTaskInvalid;
}
});
});
}
22.ScrollView滾動動畫的三種方式
- begin 和 commit
[UIView beginAnimations:nil context: nil];
[UIView setAnimationDuration:2.0];
[UIView setAnimationDelegate:self]; // 代理
[UIView setAnimationDidStopSelector:@selector(stop)];
[UIView setAnimationWillStartSelector:@selector(start)];
CGFloat offsetX = self.scrollView.contentSize.width - self.scrollView.frame.size.width;
self.scrollView.contentOffset = CGPointMake(offsetX, self.scrollView.contentOffset.y);
[UIView commitAnimations];
- block
[UIView animateWithDuration:2.0 animations:^{
self.scrollView.contentOffset = CGPointMake(0, self.scrollView.contentOffset.y);
}];
- 某些屬性有其特有的動畫
CGPoint offset = CGPointMake(self.scrollView.contentOffset.x, 0);
[self.scrollView setContentOffset:offset animated:YES];
23.RAC注銷通知的兩種方法
方法一:
//代替通知
//takeUntil會接收一個signal,當(dāng)signal觸發(fā)后會把之前的信號釋放掉
[[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardDidShowNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(id x) {
NSLog(@"鍵盤彈出");
}];
方法二:
//這里這樣寫只是為了給大家開拓一種思路,selector的方法可以應(yīng)需求更改,即當(dāng)這個方法執(zhí)行后,產(chǎn)生一個信號告知控制器釋放掉這個訂閱的信號
RACSignal * deallocSignal = [self rac_signalForSelector:@selector(viewWillDisappear:)];
[[[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"haha" object:nil] takeUntil:deallocSignal] subscribeNext:^(id x) {
NSLog(@"haha");
}];
24.消除警告
1.關(guān)于編譯器:關(guān)閉警告:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
代碼
#pragma clang diagnostic pop
2.忽略沒用的變量
#pragma unused (foo)
明確定義錯誤和警告
#error Whoa, buddy, you need to check for zero here!
#warning Dude, don't compare floating point numbers like this!
25.導(dǎo)航欄顯示和隱藏(只能進行顯示和隱藏兩者之間的切換迅矛、不能進行隱藏和隱藏之間的切換(這個有bug)
)
將animated屬性繼承ViewWillAppear(Disappear)的animated屬性即可
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[self.navigationController setNavigationBarHidden:NO animated:animated];
}
26.使用Masonry計算cell高度titleLabel
為最下面元素
//注意:這是寫這篇文章的重中之重,核心代碼
+ (CGFloat)heightWithModel:(ECHelpListModel *)model{
ECHelpListDetailCell *cell = [[ECHelpListDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
[cell setModel:model];
[cell layoutIfNeeded];
return cell.titleLabel.bottom + 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//取出model
HHPollingItemsModel *model = self.items[indexPath.row];
return [HHPollingDetailCell heightWithModel:model];
}
model 懶加載計算高度自己常用的方法
//.h
@property (nonatomic, assign) CGFloat cellHeight;
//.m
- (CGFloat)cellHeight {
// 如果cell的高度已經(jīng)計算過, 就直接返回
if (_cellHeight) return _cellHeight;
_cellHeight = 0;
_cellHeight++......// 計算高度的一系列操作
return _cellHeight;
}
//調(diào)用:
//計算cell的高度(在model里面計算)
return self.dataArray[indexPath.row].cellHeight;
參考地址:http://www.cocoachina.com/ios/20171212/21504.html
27.判斷子view是否添加到父view上
if ([subView isDescendantOfView: parentView]) {
NSLog(@"已添加上");
}
28.UIView強制賦值圖片
// 跨框架賦值需要進行橋接
self.view.layer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"123"].CGImage);
29.判斷類里面是否有實現(xiàn)某個方法
//判斷wearNeat方法有沒有在Student中實現(xiàn)了
if([stu respondsToSelector:@selector(wearNeat)]){
[stu wearNeat];
}
30.給有問題的代碼打警告
#warning 代碼過幾天在補充