1. 程式人生 > >ios UI控制元件的簡單整理

ios UI控制元件的簡單整理

/** 匿名類目:可以宣告方法和變數,屬性為private(不允許在外部呼叫,且不能被繼承 */ /** 傳送資料的委託方,接收資料的時代理髮(即代理的反向傳值) 委託方第一步:宣告協議 委託方第二步:宣告代理指標 委託方第三步:操作完成,告訴代理(即呼叫代理的方法) 代理第一步:遵守協議 代理第二步:成為代理 代理第三步:實現協議方法 */ // %zd %zi 表示NSInteger // %g 表示數字去掉尾零 //程式碼塊路徑 /Users/ms/Library/Developer/Xcode/UserData/CodeSnippets #pragma mark - Xcode快捷鍵 Control + A:移動游標到行首 Control + E:移動游標到行末 Control + D:刪除游標右邊的字元 Control + K:刪除本行 Command + ->:移動到行尾 #pragma mark - 本地化
// 找到這個倉庫 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults]; // 存放資料 [ud setObject:@"hehe" forKey:@"a"]; // 同步 [ud synchronize]; // 從ud裡通過key查詢儲存的物件(可以存放NSString,NSNumber,陣列,陣列,NSDate,NSData) // 注:ud裡不能存放自定義型別(放在容器裡也不行) NSString *str = [ud objectForKey:@"a"]; #pragma mark - 通知 NSDictionary *dic = [NSDictionary
dictionaryWithObjectsAndKeys:@"111", @"aaa", nil]; // 通過通知中心,傳送一條通知,可以用第二個引數 // 工程中所有監控fm90的物件都可以收到者個通知 [[NSNotificationCenter defaultCenter] postNotificationName:@"FM90" object:self.textView.text userInfo:dic]; // 在通知中心註冊了一個觀察者(self),當工程中任何地方傳送了FM90這個通知,self都會觸發listenUp這個方法 [[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(listenUp:) name:@"FM90" object:nil]; // 如果通知中心的觀察者回調裡有引數,引數就是NSNotification - (void)listenUp:(NSNotification *)sender { // 傳送廣播時帶的兩個引數 // NSLog(@"%@ , %@", sender.name, sender.userInfo); } - (void)dealloc { // 當觀察者dealloc的時候,需要移除觀察者身份 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"FM90" object:nil]; } #pragma mark - 獲取程式檔案相關目錄 // 獲取APP Home 目錄 NSString * homeDirectory = NSHomeDirectory(); // 獲取 檔案.app 目錄 NSString * appPath = [[NSBundle mainBundle] bundlePath]; // 獲取 Documents 目錄 NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString * path = [paths objectAtIndex:0]; // 獲取 Library 目錄 paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); path = [paths objectAtIndex:0]; // 獲取 Caches 目錄 paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); path = [paths objectAtIndex:0]; // 獲取程式資源路徑 //path = [NSBundle mainBundle] pathForResource:(NSString *)ofType:(NSString *) // 載入資源 //[[NSBundle mainBundle] loadNibNamed:@"string" owner:nil options:nil] #pragma mark - 手勢 // 找到觸控事件 UITouch *momo = [touches anyObject]; // 判斷觸控的圖片是不是圖片檢視 if ([momo.view isKindOfClass:[UIImageView class]]) { [self.view bringSubviewToFront:momo.view]; // 記錄滑鼠的原始座標(移動軌跡原始座標) _tempPoint = [momo locationInView:self.view]; } // 滑鼠點選次數 momo.tapCount /**************六種基本手勢******************/ // 點選手勢(鬆開滑鼠時響應) UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapCR:)]; // 將手勢新增到view上 [view addGestureRecognizer:tapGR]; // 拖拽(移動,拖動,move)手勢(這個手勢和清掃手勢衝突) UIPanGestureRecognizer *panGR = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGR:)]; // 縮放手勢 UIPinchGestureRecognizer *pinchGR = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchGR:)]; // 旋轉手勢 UIRotationGestureRecognizer *rotationGR = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotationGR:)]; // 長按手勢 UILongPressGestureRecognizer *longPressGR = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGR:)]; // 輕掃手勢(和移動手勢衝突) UISwipeGestureRecognizer *swipeGR = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGR:)]; // 設定輕掃方向 swipeGR.direction = UISwipeGestureRecognizerDirectionUp; // 如果想響應多個方向的清掃需要建立多個清掃手勢的物件 UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGR:)]; // 設定輕掃方向 swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft; // 輕掃 - (void)swipeGR:(UISwipeGestureRecognizer *)swipeGR { CGRect frame = swipeGR.view.frame; // 判斷輕掃方向 if (swipeGR.direction == UISwipeGestureRecognizerDirectionUp) { frame.size.height += 10; } // 按位與判斷(用數字1進行按位與運算的結果,可以用按位與來判斷是否相等) if (swipeGR.direction & UISwipeGestureRecognizerDirectionLeft) { frame.size.height -= 10; } } // 長按 - (void)longPressGR:(UILongPressGestureRecognizer *)longPressGR { // 判斷手勢狀態 if (longPressGR.state == UIGestureRecognizerStateBegan) } // 旋轉 - (void)rotationGR:(UIRotationGestureRecognizer *)rotationGR { // 讓view旋轉,後面一個引數就是旋轉的角度 rotationGR.view.transform = CGAffineTransformRotate(rotationGR.view.transform, rotationGR.rotation); // 每次旋轉以後需要將記錄還原 rotationGR.rotation = 0; } // 縮放 - (void)pinchGR:(UIPinchGestureRecognizer *)pinchGR { // 讓view縮放,後面2個引數,一個是x方向縮放的倍數,一個是y方向縮放的倍數 pinchGR.view.transform = CGAffineTransformScale(pinchGR.view.transform, pinchGR.scale, pinchGR.scale); // 每次縮放後需要還原倍數的記錄 pinchGR.scale = 1.0; } // 移動 - (void)panGR:(UIPanGestureRecognizer *)panGR { // 移動手勢對應的訊息(x方向移動多少,y方向移動多少) CGPoint point = [panGR translationInView:self.view]; // 根據軌跡修改手勢對應的view panGR.view.center = CGPointMake(panGR.view.center.x + point.x, panGR.view.center.y + point.y); // 每次移動以後需要將手勢的軌跡清零 [panGR setTranslation:CGPointMake(0, 0) inView:self.view]; } // 點選 - (void)tapCR:(UITapGestureRecognizer *)tagRG { [self.view bringSubviewToFront:tagRG.view]; } #pragma mark - 圖片擷取 - (UIImage *)clipImage:(UIImage *)image inRect:(CGRect)rect {//返回image中rect範圍內的圖片 CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, rect); UIImage *subImage = [UIImage imageWithCGImage:imageRef]; return subImage; } #pragma mark - 計算字串尺寸 // 計算一個字串完整展示所需要的size // 第一個引數是最大不能超過的size // 第二個引數固定寫法 // 第三個引數是計算size時字串的屬性 CGSize size = [str boundingRectWithSize:CGSizeMake(width - 5, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:self.label.font, NSFontAttributeName, nil] context:nil].size; // 根據計算的結果修改label的frame CGRect frame = self.label.frame; frame.size.width = size.width + 5; frame.size.height = size.height + 5; self.label.frame = frame; #pragma mark - 動畫 #pragma mark -簡單動畫 /** 動畫1 **/ // 簡單動畫,可以修改frame,alpha(透明度1.0),背景色 // 完成frame修改的動作需要兩秒,但是程式碼不會卡住,程式碼會繼續執行 [UIView animateWithDuration:2 animations:^{ bigView.frame = frame; }]; /** 動畫2 **/ [UIView animateWithDuration:2 animations:^{ bigView.frame = frame; } completion:^(BOOL finished) { NSLog(@"動畫完成以後的回撥=%d",finished); }]; /** 動畫3 **/ // 開始簡單動畫 [UIView beginAnimations:nil context:NULL]; // 設定動畫時間 [UIView setAnimationDuration:2]; //... 新增程式碼,屬於要展示動畫的區域 // 提交動畫 [UIView commitAnimations]; /** 跟隨模式 **/ /* UIViewAutoresizingNone = 0, UIViewAutoresizingFlexibleLeftMargin = 1 << 0, UIViewAutoresizingFlexibleWidth = 1 << 1, UIViewAutoresizingFlexibleRightMargin = 1 << 2, UIViewAutoresizingFlexibleTopMargin = 1 << 3, UIViewAutoresizingFlexibleHeight = 1 << 4, UIViewAutoresizingFlexibleBottomMargin = 1 << 5 */ // 允許子檢視跟隨 bigView.autoresizesSubviews = YES; // 子檢視跟隨的模式 smallView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; #pragma mark -基礎動畫 /***************CABasicAnimation************/ // 建立核心動畫 // 縮放比例用transform.scale //transform.scale代表縮放(倍數) //transform.rotation.x transform.rotation.y transform.rotation.z 代表旋轉(角度) CABasicAnimation *ani = [CABasicAnimation animationWithKeyPath:@"transform.rotation.y"]; // 動畫的始末值 // @0.5 相當於 [NSNumber numberWithFloat:0.5] ani.fromValue = @0; ani.toValue = @M_PI; // 單次動畫時間 ani.duration = 2; // 重複次數 ani.repeatCount = 10; // 動畫返回形式 ani.autoreverses = YES; // 新增動畫 [view.layer addAnimation:ani forKey:@"aaa"]; // 移除動畫 [longPressGR.view.layer removeAnimationForKey:@"aaa"]; #pragma mark -轉場動畫 // 建立轉場動畫 CATransition *tt = [CATransition animation]; // 動畫時間 tt.duration = 2; // 方向 tt.subtype = kCATransitionFromBottom; //四種預設,某些型別中此設定無效 kCATransitionFromRight kCATransitionFromLeft kCATransitionFromTop kCATransitionFromBottom // 型別(系統自帶的有4個) tt.type = kCATransitionMoveIn; tt.type = @"rotate"; /* 1----> #define定義的常量(基本型) kCATransitionFade 交叉淡化過渡 kCATransitionMoveIn 新檢視移到舊檢視上面 kCATransitionPush 新檢視把舊檢視推出去 kCATransitionReveal 將舊檢視移開,顯示下面的新檢視 2---> 蘋果官方自定義型別: fade moveIn push reveal 和上面的四種一樣 pageCurl pageUnCurl 翻頁 rippleEffect 滴水效果 suckEffect 收縮效果,如一塊布被抽走 cube alignedCube 立方體效果 flip alignedFlip oglFlip 翻轉效果 rotate 旋轉 cameraIris cameraIrisHollowOpen cameraIrisHollowClose 相機 */ [self.navigationController.view.layer addAnimation:tt forKey:nil]; [self.navigationController pushViewController:dvc animated:NO]; #pragma mark - UIApplication openURL: ● UIApplication有個功能⼗十分強⼤大的openURL:⽅方法 - (BOOL)openURL:(NSURL*)url; ● openURL:⽅方法的部分功能有 ➢ 打電話 UIApplication *app = [UIApplication sharedApplication]; [app openURL:[NSURL URLWithString:@"tel://10086"]]; ➢ 發簡訊 [app openURL:[NSURL URLWithString:@"sms://10086"]]; ➢ 發郵件 [app openURL:[NSURL URLWithString:@"mailto://[email protected]"]]; ➢ 開啟⼀一個⺴⽹網⻚頁資源 [app openURL:[NSURL URLWithString:@"http://ios.itcast.cn"]]; #pragma mark - UIView // frame設定需要有中間值 CGRect frame = bigView.frame; frame.size.width *= 2; frame.size.height *= 2; bigView.frame = frame; // 圓角 bigView.layer.cornerRadius = 150; // 角度設為frame.width/height則是個圓 bigView.clipsToBounds = YES; // 邊框 bigView.layer.borderWidth = 2; bigView.layer.borderColor = [[UIColor blackColor] CGColor]; // 設定背景圖片 self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Default"]]; /* //相對父檢視的座標 @property(nonatomic) CGRect frame; //相對於自己內容的座標 @property(nonatomic) CGRect bounds; //父檢視 @property(nonatomic,readonly) UIView *superview; //所有的子檢視 @property(nonatomic,readonly,copy) NSArray *subviews; //內容模式(填充一邊位等比例模式) @property(nonatomic) UIViewContentMode contentMode; // default UIViewContentModeScaleToFill //在最上層新增一個檢視 - (void)addSubview:(UIView *)view; //在指定層面插入一個檢視(如果層級越界,就相當於add) - (void)insertSubview:(UIView *)view atIndex:(NSInteger)index; //在某個檢視是下級插入一個新檢視 - (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview; //在某個檢視的上級插入一個新檢視 - (void)insertSubview:(UIView *)view aboveSubview:(UIView *)siblingSubview; //從父檢視中移除(自殺) - (void)removeFromSuperview; //修改2個檢視的層級 - (void)exchangeSubviewAtIndex:(NSInteger)index1 withSubviewAtIndex:(NSInteger)index2; //將某個檢視移到最上層 - (void)bringSubviewToFront:(UIView *)view; //將某個視力移到最底層 - (void)sendSubviewToBack:(UIView *)view; //判斷一個檢視是否是別外一個檢視的子檢視(如果是同一個檢視也會返回yes) - (BOOL)isDescendantOfView:(UIView *)view; //通過tag找view - (UIView *)viewWithTag:(NSInteger)tag; */ #pragma mark - UILabel /* //設定文字 @property(nonatomic,copy) NSString *text; //文字顏色 @property(nonatomic,retain) UIColor *textColor; //陰影顏色 @property(nonatomic,retain) UIColor *shadowColor; //陰影座標 @property(nonatomic) CGSize shadowOffset; //將label大小調整為單行展示文字所需要的大小 - (void)sizeToFit; //對齊方式 @property(nonatomic) NSTextAlignment textAlignment; //換行方式省略號位置 @property(nonatomic) NSLineBreakMode lineBreakMode; //行數,預設是1,設為0後自動換行 @property(nonatomic) NSInteger numberOfLines; //字型 @property(nonatomic,retain) UIFont *font; */ // 不能自動換行,但能增加長度 [self.label sizeToFit]; //使用固定字型 label.font = [UIFont fontWithName:@"Zapfino" size:20]; //系統預設字型 label.font = [UIFont systemFontOfSize:20]; //系統預設字型加黑 label.font = [UIFont boldSystemFontOfSize:20]; //系統預設字型斜體 label.font = [UIFont italicSystemFontOfSize:20]; #pragma mark - UIButton // btn的型別,除了custom和system,另外4個都自帶大小和外觀 UIButton *btn = [UIButton buttonWithType:UIButtonTypeInfoDark]; // 設定文字垂直和水平的對齊方式 btn.titleLabel.font = [UIFont systemFontOfSize:15]; btn.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom; btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; // 當btn接收到TouchUpInside這個事件時,會給self傳送btnClick這個訊息 // 事件-訊息機制 [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside]; #pragma mark - UIImageView // 圖片轉為NSData UIImagePNGRepresentation(_ivView.image) // 圖片轉為點陣圖(防止渲染) [_ivView.image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]; // 顯示圖片大小為imageView大小 _starsView.contentMode = UIViewContentModeLeft; _starsView.clipsToBounds = YES; // 設定影象填充模式,等比例顯示(CTRL+6) iv.contentMode = UIViewContentModeScaleAspectFit; // 從iPhone4開始,裝置的螢幕都是retina屏(2倍,一個座標位橫向縱向顯示2個畫素點,高清屏,視網膜屏),(6p是3倍的) // retina螢幕會優先找[email protected],找不到就找a.png iv.image = [UIImage imageNamed:@"a"]; // 圖片物件(自帶的大小是座標體系的大小,如果用的是@2x圖片,畫素大小的寬高除以2就是座標體系的大小 UIImage *image = [UIImage imageNamed:@"c"]; // 用圖片直接建立圖片檢視,x,y預設是0,寬高預設是圖片的大小 UIImageView *secondIv = [[UIImageView alloc] initWithImage:image]; /** 圖片輪播 **/ // 設定圖片檢視輪播圖片的陣列,單次動畫時間,迴圈次數(預設無線迴圈,0次也是無線迴圈),開始動畫 iv.animationImages = tempArr; iv.animationDuration = tempArr.count/10.0f; iv.animationRepeatCount = 0; [iv startAnimating]; /* //開始動畫 - (void)startAnimating; //手動結束動畫 - (void)stopAnimating; //判斷動畫狀態 - (BOOL)isAnimating; //圖片 @property(nonatomic,retain) UIImage *image; //動畫的圖片陣列 @property(nonatomic,copy) NSArray *animationImages; //動畫時間(也就是一次完整的動畫需要的時間) @property(nonatomic) NSTimeInterval animationDuration; //動畫迴圈次數,迴圈完以後會自動停止 @property(nonatomic) NSInteger animationRepeatCount; */ #pragma mark - UITextFiled // 佔位提示符 tf.placeholder = @"請輸入QQ號"; // 邊框風格 tf.borderStyle = UITextBorderStyleLine; // 背景圖片(和邊框風格衝突) // 如果風格是圓角,那麼背景圖片失效 // 如果邊框風格不是圓角,那麼邊框風格失效 tf.background = [UIImage imageNamed:@"tf_bg"]; // 當字串的長度超過tf的長度,可以自動縮小字型 tf.adjustsFontSizeToFitWidth = YES; // 自動縮小的最小值 tf.minimumFontSize = 30; // 水平方向的對齊方式(同label) tf.textAlignment = NSTextAlignmentRight; // 垂直方向對齊方式(同button) tf.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom; // 當字串的長度超過tf的長度,可以自動縮小字型 tf.adjustsFontSizeToFitWidth = YES; // 自動縮小的最小值 tf.minimumFontSize = 30; // 水平方向的對齊方式(同label) tf.textAlignment = NSTextAlignmentRight; // 垂直方向對齊方式(同button) tf.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom; // 當彈出鍵盤的時候,清空tf的文字 tf.clearsOnBeginEditing = YES; // 設定清空按鈕出現的方式 tf.clearButtonMode = UITextFieldViewModeWhileEditing; // 安全輸入(暗文輸入,專門輸入密碼使用) tf.secureTextEntry = YES; // 鍵盤型別 tf.keyboardType = UIKeyboardTypeDefault; // 回車鍵的外觀(和功能沒有任何關係) tf.returnKeyType = UIReturnKeyNext; // 設定tf的左邊的附屬view的出現模式(實際工作中一般都是圖片imageview) // 一個view只能成為一個地方的附屬view tf.leftView = view; tf.leftViewMode = UITextFieldViewModeAlways; // 鍵盤view和附屬view tf.inputView = view; tf.inputAccessoryView = view; // 收起這個頁面的鍵盤 [self.view endEditing:YES]; // 放棄第一響應 [self.view resignFirstResponder] #pragma mark - UIViewController // 第一種跳轉 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { // 通過連線的識別符號來執行某個跳轉 // segue過渡的意思 [self performSegueWithIdentifier:@"PushToCyan" sender:nil]; } // 第二種跳轉 // 通過storyboard跳轉頁面時都會走這個方法 // 第一個引數就是跳轉的那根連線,第二個引數暫時理解成觸發跳轉的物件(storyboard裡已經畫出的view) - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // 通過連線找到跳轉到的頁面 UIViewController *nextVC = [segue destinationViewController]; nextVC.view.backgroundColor = [UIColor yellowColor]; // self.tableView就是表格頁面自動帶的tableview // 在一個tableView裡通過cell找到所處的位置 MovieCell *cell = (id)sender; NSIndexPath *path = [self.tableView indexPathForCell:cell]; } // 第三種跳轉 // 找到自帶的Main.storyboard UIStoryboard *sd = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; UIViewController *vc = [sd instantiateViewControllerWithIdentifier:@"Cyan"]; [self.navigationController pushViewController:vc animated:YES]; // 宣告週期 3-->-[ThirdViewController initWithNibName:bundle:] 3-->-[ThirdViewController viewDidLoad] 3-->-[ThirdViewController viewWillAppear:] 3-->-[ThirdViewController viewDidAppear:] -[FourthViewController initWithNibName:bundle:] -[FourthViewController viewDidLoad] 3-->-[ThirdViewController viewWillDisappear:] -[FourthViewController viewWillAppear:] 3-->-[ThirdViewController viewDidDisappear:] -[FourthViewController viewDidAppear:] -[FourthViewController viewWillDisappear:] 3-->-[ThirdViewController dealloc] -[FourthViewController viewDidDisappear:] -[FourthViewController dealloc] //彈出一個新的viewController - (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^)(void))completion; //銷燬當前viewcontroller - (void)dismissViewControllerAnimated: (BOOL)flag completion: (void (^)(void))completion; #pragma mark - UINavigationController // 設定導航欄(導航欄是屬於導航控制器的) // 導航欄分為兩部分(工具條高 20,以下高44) // 針對導航欄的設定,全影響到整個導航控制器 // 設定導航欄的隱藏狀態 self.navigationController.navigationBarHidden = NO; // 通過vc找到nc,通過nc找到導航欄,設定背景色 self.navigationController.navigationBar.barTintColor = [UIColor magentaColor]; // 設定導航欄內容的渲染色(自帶的返回按鈕) self.navigationController.navigationBar.tintColor = [UIColor greenColor]; // 半透明狀態,如果寫成YES,(0,0)座標點在導航欄的左上角 // 如果寫成NO,(0,0)座標點在導航欄的左下角 self.navigationController.navigationBar.translucent = NO; // 設定背景圖(平鋪模式:即如果圖片過小,重複顯示)(會引起座標原點的改變) // 以iPhone為例,如果圖片size是320*44,那麼就會展示成ios7以前的效果(系統狀態列和導航欄完全分離) [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"aaa"] forBarMetrics:UIBarMetricsDefault]; // 這個方法可以獲取當前導航欄 [UINavigationBar appearance]; // 設定導航欄title的文字屬性 self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:10], NSFontAttributeName, [UIColor purpleColor], NSForegroundColorAttributeName, nil]; // 展示在當前頁導航欄正中間的view,設定了這個view,title就不顯示了 self.navigationItem.titleView = label; /* 4種建立專用按鈕 a,使用字串建立 b,使用圖片(預設會被渲染,需要注意圖片的大小寫) c,使用系統自帶的風格 d,自定義(一般都用UIButton) */ UIBarButtonSystemItemFlexibleSpace,是自帶的一種空的item,可以當作佔位符用 [[UIImage imageNamed:@"gerenzhuye"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal],去除圖片的渲染 // 將專有按鈕放到當前導航欄的左邊 UIBarButtonItem *aItem = [[UIBarButtonItem alloc] initWithTitle:@"aItem" style:UIBarButtonItemStylePlain target:self action:@selector(itemClick)]; [aItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:10], NSFontAttributeName, nil] forState:UIControlStateNormal]; self.navigationItem.leftBarButtonItem = aItem; // 使用圖片建立專用按鈕(只取輪廓,不取顏色,系統會把不透明的地方渲染了)(預設渲染色為藍色) UIBarButtonItem *bItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"haoyou"] style:UIBarButtonItemStyleDone target:self action:@selector(itemClick)]; // 使用系統自帶的風格 UIBarButtonItem *cItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(itemClick)]; // 使用view建立專有按鈕(一般用btn,只有用btn才能新增監聽事件) UIBarButtonItem *dItem = [[UIBarButtonItem alloc] initWithCustomView:btn]; // 系統自定義按鈕 self.navigationItem.leftBarButtonItem = self.editButtonItem; #pragma mark - UITabBarController /* 使用tabBarController的基本思路 1,建立所有展示的頁面 2,如果需要將頁面放到導航裡 3,設定每個頁面或者導航顯示到tabBar上的專用按鈕 4,將頁面或者導航放到數組裡,並且和標籤欄控制器關聯 */ // 初始化分欄控制器(標籤欄控制器) UITabBarController *tbc = [[UITabBarController alloc] init]; // 設定需要控制的頁面(可以是普通頁面,也可以是導航控制器) tbc.viewControllers = [NSArray arrayWithObjects:av, bnc, cv, dv, ev, fv, gv, nil]; // 推出新頁面的時候,隱藏底層標籤欄,返回的時候會自動出現 gv.hidesBottomBarWhenPushed = YES; /* 建立專用按鈕的3中方式 */ // 建立一個標籤欄的專用按鈕(系統自帶樣式) UITabBarItem *homeItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemContacts tag:0]; homeNC.tabBarItem = homeItem; // 使用一個字串和一個圖片建立專用按鈕(預設渲染圖片) // UITabItem使用的圖片最合適的大小是30*30 UITabBarItem *loveItem = [[UITabBarItem alloc] initWithTitle:@"love" image:[UIImage imageNamed:@"tab_0"] tag:0]; // 使用一個字串和2張圖片建立(預設會渲染) UITabBarItem *nearlyItem = [[UITabBarItem alloc] initWithTitle:@"nearly" image:[UIImage imageNamed:@"tab2_1"] selectedImage:[UIImage imageNamed:@"tab2_2"]]; // 設定渲染色 UITabBarController.tabBar.tintColor = [UIColor redColor]; // 設定背景顏色 UITabBarController.tabBar.barTintColor = [UIColor cyanColor]; // 背景圖片 UITabBarController.tabBar.backgroundImage = [UIImage imageNamed:@"tabbg"]; // 顯示字型屬性,字型屬性單獨設定 [homeItem setTitleTextAttributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:10] forKey:NSFontAttributeName] forState:UIControlStateNormal]; // 讓分欄控制器裡對應的頁面,展示出來 self.selectedIndex = sender.tag - 100; #pragma mark - UIScrollView // 設定滾動試圖內可以展示的最大的size sv.contentSize = CGSizeMake(480, 480); // 設定偏移量(偏移就是位移,現在展示的子檢視和預設子檢視相比移動的距離) sv.contentOffset = CGPointMake(20, 20); // 水平和垂直方向的進度條 // 在有些版本里,垂直隱藏,水平也就不顯示了 sv.showsHorizontalScrollIndicator = NO; sv.showsVerticalScrollIndicator = NO; // 彈簧效果 sv.bounces = NO; // 代理方法中的bool值 // decelerate代表鬆手以後sv是否會繼續滑行(1代表會) // 如果頁面實在導航裡,而且第一個子檢視是sv,那麼系統會讓這個sv有一個自動下沉的效果 self.automaticallyAdjustsScrollViewInsets = NO; // sv中只能有一個子檢視可以被縮放 // 如果sv中有多個子檢視,縮放的時候會對整個sv產生不可預料的後果 // 最大、最小縮放倍數 sv.minimumZoomScale = 0.5; sv.maximumZoomScale = 2; // 放大縮小的代理 - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { return [scrollView viewWithTag:1]; } #pragma mark - UIPageControl // 翻頁控制器 UIPageControl *pc = [[UIPageControl alloc] initWithFrame:CGRectMake(100, 450, 0, 0)]; // 根據頁數自動分配大小 [pc sizeForNumberOfPages:5]; // 設定頁數 pc.numberOfPages = 5; // 小點點的顏色 pc.currentPageIndicatorTintColor = [UIColor redColor]; pc.pageIndicatorTintColor = [UIColor greenColor]; // 一般關閉使用者互動 pc.userInteractionEnabled = NO; #pragma mark - UITableView // 註冊複用標示符 [_myTableView registerClass:[BookCell class] forCellReuseIdentifier:@"cell"]; [_myTableView registerNib:[UINib nibWithNibName:@"BookCell" bundle:nil] forCellReuseIdentifier:@"cell"]; // 自動下沉,(繼承與scrollview,符合其特性) self.automaticallyAdjustsScrollViewInsets = NO; // 分割線顏色 _myTableView.separatorColor = [UIColor redColor]; // 通過tableview找到cell UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; // 設定cell點選以後是否變灰,如果引數設成NONE就不變,否則就變 cell.selectionStyle = UITableViewCellSelectionStyleNone; // cell的附屬view的型別(如果附屬view裡有btn,那麼這個view的點選事件就會獨立出來) // 代理有事件響應方法 cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton; // 自定義附屬view // cell.accessoryView // 腳標題行高 - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section; - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section; - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; // 自定義頭標題的view(view的會替換自帶的頭標題view) // frame設定無效,位置固定,寬度固定和table一樣,高度通過代理方法設定 - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section; // 設定小節數,預設為1 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; // cell被點選時促發 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // 讓cell被選中變灰的狀態,恢復成沒變灰的狀態 [tableView deselectRowAtIndexPath:indexPath animated:YES]; } // 與上相反,一般不用 - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath; // 如果cell的附屬view裡有btn,那麼這個view的點選事件會獨立出來 - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath; #pragma -編輯相關 // 重新整理,重新載入資料 [_myTableView reloadData]; // 每次點選都改變tv的編輯狀態 // 修改刪除按鈕上的文字 - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath; // 允許編輯,編輯相關的按鈕(刪除,插入)點選時觸發 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // 通過位置先刪除對應的資料模型 [[_dataArr objectAtIndex:indexPath.section] removeObjectAtIndex:indexPath.row]; [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft]; } if (editingStyle == UITableViewCellEditingStyleInsert) { Person *person = [[Person alloc] init]; // 在資料對應位置插入資料 [[_dataArr objectAtIndex:indexPath.section] insertObject:person atIndex:indexPath.row]; // 在對應的位置插入一個cell(會自動匹配剛剛插入的資料) [_myTableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft]; } } // 設定cell的編輯風格 - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath; // 返回刪除和插入按位或(其實即使3),就是多選刪除 //return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert; // 移動單元格 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath { // 通過移動前的位置找到將要移動的資料模型 Person *person = [[_dataArr objectAtIndex:sourceIndexPath.section] objectAtIndex:sourceIndexPath.row]; // 把資料來源刪除 [[_dataArr objectAtIndex:sourceIndexPath.section] removeObject:person]; // 插入源位置 [[_dataArr objectAtIndex:destinationIndexPath.section] insertObject:person atIndex:destinationIndexPath.row]; } // self.editButtonItem的點選事件 // UIViewController自帶的方法 - (void)setEditing:(BOOL)editing animated:(BOOL)animated { // 必須呼叫一次父類的(類似viewDidLoad) [super setEditing:editing animated:YES]; [_myTableView setEditing:editing animated:YES]; } // 索引條 // 預設情況下點選索引裡的第幾個,tv就會跳到第幾段 - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { NSMutableArray *titleArr = [NSMutableArray array]; for (int i = 'A'; i <= 'Z'; i++) { [titleArr addObject:[NSString stringWithFormat:@"%c", i]]; } return titleArr; } // 索引顏色 //@property(nonatomic, retain) UIColor *sectionIndexColor NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR; // color used for text of the section index //@property(nonatomic, retain) UIColor *sectionIndexBackgroundColor NS_AVAILABLE_IOS(7_0) UI_APPEARANCE_SELECTOR; // the background color of the section index while not being touched //@property(nonatomic, retain) UIColor *sectionIndexTrackingBackgroundColor NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR; // the background color of the section index while it is being touched #pragma mark - UICollectionView // 網格檢視需要一個佈局來支撐自己 UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; // 設定滾動方向(預設就是垂直方向) layout.scrollDirection = UICollectionViewScrollDirectionHorizontal; // 註冊 [_myCollection registerClass:[MyCell class] forCellWithReuseIdentifier:@"cell"]; [_myCollection registerClass:[MyView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"]; - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section; - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { // 網格檢視的cell必須提前註冊 MyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath]; cell.label.text = [NSString stringWithFormat:@"第%d個", indexPath.row]; cell.iconView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%d.jpg", indexPath.row]]; return cell; } // 設定單個cell的大小 - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath; // 設定cell的分組 - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView; // 設定cell之間水平最小間隔 - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section; // 設定分段內部cell之間垂直最小間隔 // 滑動方向的間距