你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> ios UI控件的簡單整理

ios UI控件的簡單整理

編輯:IOS開發綜合

把該文件復制到.m文件裡就能夠方便的查找


/**
 匿名類目:可以聲明方法和變量,屬性為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之間垂直最小間隔
// 滑動方向的間距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section;
// 設置分段之間的邊距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;
// 設置段頭或者段尾
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    // 判斷是段頭還是短尾
    //    if (kind == UICollectionElementKindSectionFooter)
    MyView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
}

// 設置段頭的大小(如果collectionView是垂直方向滑動,那麼寬度會被忽略,系統會自動匹配成collectionView的寬度)
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section;
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath;

#pragma mark - UIToolbar

// 工具欄(在工具欄上可以放導航專用按鈕)
UIToolbar *tb = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 20, 320, 44)];
[self.view addSubview:tb];
UIBarButtonItem *editBtn =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(editClick:)];
// UIBarButtonSystemItemFlexibleSpace專用按鈕占位符
// 在工具欄展示一些專用按鈕
tb.items = @[editBtn, refreshBtn];

#pragma mark - UISearchBar

_sb = [[UISearchBar alloc] initWithFrame:frame];
// 整個表格視圖可以擁有一個頭view
_myTableView.tableHeaderView = _sb;

// 搜索控制器(將_sb和頁面關聯起來)
_sdc = [[UISearchDisplayController alloc] initWithSearchBar:_sb contentsController:self];
_sdc.delegate = self;
// 給搜索控制器自帶的tableView設置代理
_sdc.searchResultsDataSource = self;
_sdc.searchResultsDelegate = self;

// 只要_sb裡的文字發生了改變,都會執行該方法
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [_resultArr removeAllObjects];
    for (NSArray *arr in _myDataArr) {
        for (NSString *str in arr) {
            NSRange range = [str rangeOfString:searchString];
            if (range.length > 0) {
                [_resultArr addObject:str];
            }
        }
    }
    return YES;
}


#pragma mark - 定時器和延時調用

//創建定時器,每隔幾秒就運行某個函數一次
NSTimer *_timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(run) userInfo:nil repeats:YES];

// 相當於上面一行
_timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(update:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];

//取消定時器(定時器取消後,必去重新初始化)
[_timer invalidate];
// self會在2秒以後執行runLater:方法,同時把sender作為參數
[self performSelector:@selector(runLater:) withObject:sender afterDelay:0.5];

#pragma mark - 常用基本控件
#pragma mark UISlider
// 滑尺控件
UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(40, 60, 240, 90)];
[self.view addSubview:slider];

// 滑尺一般情況下我們是監控ValueChanged事件
// 可以添加多個監聽事件
[slider addTarget:self action:@selector(sliderClick:) forControlEvents:UIControlEventValueChanged];
// ValueChanged事件對應的消息在滑動過程中是否接收
slider.continuous = NO;

// 最小和最大記錄的值(記錄范圍)
slider.maximumValue = 10;
slider.minimumValue = 0;
// 通過代碼設置滑塊的值
slider.value = 5;

// 左右線條的顏色
slider.maximumTrackTintColor = [UIColor blackColor];
slider.minimumTrackTintColor = [UIColor greenColor];

// 設置小圓圈(拇指)圖片
[slider setThumbImage:[UIImage imageNamed:@"gerenzhuye"] forState:UIControlStateNormal];

#pragma mark UISegmentedControl

// 使用數組初始化分段選擇器(可以是字符串,也可以是圖片,圖片默認被渲染)
UISegmentedControl *segmentControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"111", [[UIImage imageNamed:@"gerenzhuye"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal],@"222", nil]];
segmentControl.frame = CGRectMake(40, 200, 240, 60);
[segmentControl addTarget:self action:@selector(segmentedControlClick:) forControlEvents:UIControlEventValueChanged];
// 刪除一個分段
[segmentControl removeSegmentAtIndex:1 animated:YES];
// 插入一個分段(可以是字符串或者圖片)
[segmentControl insertSegmentWithTitle:@"333" atIndex:2 animated:YES];
// 設置默認點擊分段
segmentControl.selectedSegmentIndex = 1;
// 設置渲染色
segmentControl.tintColor = [UIColor redColor];

// 獲取分段的位置編號
// 獲取分段的標題
sc.selectedSegmentIndex;
[sc titleForSegmentAtIndex:sc.selectedSegmentIndex];

#pragma mark UISwitch

// 開關控件,大小是固定的51*31,自己設定無效
UISwitch *open = [[UISwitch alloc] initWithFrame:CGRectMake(40, 80, 100, 100)];
// 拇指,關閉時邊框,打開時背景的顏色
open.thumbTintColor = [UIColor redColor];
open.tintColor = [UIColor blackColor];
open.onTintColor = [UIColor blueColor];
// 默認打開狀態
open.on = YES;

#pragma mark UIActivityIndicatorView

// 使用某種風格初始化活動指示器(自帶大小)
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
// 開始旋轉
[indicator startAnimating];
// 一般都是放置在屏幕正中間
indicator.center = self.view.center;
// 設置小菊花顏色
indicator.color = [UIColor yellowColor];

// 用系統提供的單例方法獲取到程序剛運行時創建的UIApplication對象
// 系統狀態欄自帶的旋轉小菊花
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

#pragma mark UIWebView

// 將字符串轉成網址類對象
NSURL *url = [NSURL URLWithString:str];
// 使用一個網址生成一個網絡請求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 讓一個網頁視圖開始加載一個網絡請求
[webView loadRequest:request];
// 允許頁面縮放
webView.scalesPageToFit = YES;

- (void)reload;
- (void)stopLoading;
- (void)goBack;
- (void)goForward;

#pragma mark UIStepper

// 計步器,大小固定94*29,設置大小無效
UIStepper *stepper = [[UIStepper alloc] initWithFrame:CGRectMake(40, 60, 200, 40)];

// 計步器每次改變的大小
stepper.stepValue = 30;
// 設置最小和最大的記錄
stepper.minimumValue = 10;
stepper.maximumValue = 300;
// 設置渲染色
stepper.tintColor = [UIColor redColor];
// 設置加號和減號的圖片
[stepper setIncrementImage:[UIImage imageNamed:@"haoyou"] forState:UIControlStateNormal];
[stepper setDecrementImage:[UIImage imageNamed:@"liaotian"] forState:UIControlStateNormal];

#pragma mark UIProgressView

// 進度條(展示用的)高度固定位2
UIProgressView *pv = [[UIProgressView alloc] initWithFrame:CGRectMake(20, 300, 280, 80)];
[pv setProgress:(sender.value-10)/290.0 animated:YES];

#pragma mark  UIAlertView

// alertView的點擊事件(必須遵守協議,成為代理才能響應)
// 如果一個頁面有多個av,在點擊事件裡,需要先通過av的tag值區分出點擊的是哪一個av,然後再通過buttonIndex區分出點擊了av的哪一個按鈕
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"標題" message:@"信息" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"其他",@"其他2", nil];
[av show];
// 代理一般實現方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;
// 添加文本輸入框
av.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;

#pragma mark UIActionSheet

// 創建一個事件列表
UIActionSheet *as = [[UIActionSheet alloc] initWithTitle:@"title" delegate:self cancelButtonTitle:@"cancel" destructiveButtonTitle:@"dt" otherButtonTitles:@"qq", @"weixin", @"weibo", nil];
// 展示的view必須是出現在window裡的
[as showInView:self.view];
  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved