人過留名教硫,雁過留聲,當自己老了回首今朝辆布,假如有這么個記錄著自己成長的簡書瞬矩,應該也是別有一番感受吧!記錄自己成長的點點滴滴锋玲,每天進步一點點景用,終會達到自己夢想的彼岸!
1嫩絮、設置UITextField的placeholder字體的顏色和字號
textField.placeholder = @"請輸入用戶名";
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
// <#注釋#>
2丛肢、創(chuàng)建按鈕添加拖動和點擊事件
//添加點擊事件
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
//添加拖動事件
[btn addTarget:self action:@selector(dragMoving:withEvent:)forControlEvents: UIControlEventTouchDragInside];
//添加拖動結束時的事件
[btn addTarget:self action:@selector(dragEnded:withEvent:)forControlEvents: UIControlEventTouchUpInside];
/**
*事件
*/
//拖動過程中
- (void)dragMoving:(UIControl *)c withEvent:ev
{
CGPoint point = [[[ev allTouches] anyObject] locationInView:self.view];
point.x = MIN(MAX(point.x, btn.width * 0.5 + 10) , self.view.width - btn.width * 0.5 - 10);//范圍
point.y = MIN(MAX(point.y, 100), self.view.height - btn.height * 0.5 - 10);//范圍
c.center = point;
_isClick = NO;
}
//拖動結束
- (void)dragEnded:(UIControl *)c withEvent:ev
{
XDLog(@"dragEnded....");
CGPoint point = [[[ev allTouches] anyObject] locationInView:self.view];
point.x = MIN(MAX(point.x, btn.width * 0.5 + 10), self.view.width - btn.width * 0.5 - 10);//范圍
point.y = MIN(MAX(point.y, 100) , self.view.height - btn.height * 0.5 - 10);//范圍
c.center = point;
[UIView animateWithDuration:0.2 animations:^{
c.centerX = c.centerX < self.view.width - c.centerX ? 30 : self.view.width - 30;
}];
_isClick = YES;
}
//點擊事件
- (void)btnClick:(UIButton *)btn
{
if (_isClick) {
//點擊方法
}
}
3、判斷是否同一日
- (BOOL)isSameDay:(NSDate*)date1 date2:(NSDate*)date2
{
NSCalendar* calendar = [NSCalendar currentCalendar];
unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];
return [comp1 day] == [comp2 day] &&
[comp1 month] == [comp2 month] &&
[comp1 year] == [comp2 year];
}
4剿干、禁止橫屏
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
return UIInterfaceOrientationMaskPortrait;
}
5、電池狀態(tài)欄改變顏色
[self.navigationController.navigationBar setBarStyle:UIBarStyleBlack];
默認的黑色(UIStatusBarStyleDefault)
白色(UIStatusBarStyleLightContent)
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
6穆刻、UITableView的Group樣式下頂部空白處理
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
self.tableView.tableHeaderView = view;
#pragma mark - 處理導航欄下1px橫線
_imageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
return (UIImageView *)view;
}
for (UIView *subview in view.subviews) {
UIImageView *imageView = [self findHairlineImageViewUnder:subview];
if (imageView) {
return imageView;
}
}
return nil;
}
//UITableView點擊一下就出現(xiàn)灰色但是立馬消失掉置尔。
//點擊那一刻可以指示出點擊了哪一行,灰色停留一秒鐘消失掉氢伟。
//1.設置cell點擊時候為灰色
cell.selectionStyle = UITableViewCellSelectionStyleGray;
//2.在tableView代理方法didSelectedRow方法這樣寫
- (void)tableView:(UITableView *)tableView didSelecteRowAtIndexPath:(NSIndexPath *)indexPath{
[ tableView deselectRowAtIndexPath:indexPath animated:YES];//直接取消選中這一行
}
7榜轿、對圖片尺寸進行壓縮
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
// Create a graphics image context
UIGraphicsBeginImageContext(newSize);
// Tell the old image to draw in this new context, with the desired
// new size
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
// Get the new image from the context
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
// End the context
UIGraphicsEndImageContext();
// Return the new image.
return newImage;
}
8、虛線圖片
- (UIImage *)imageWithSize:(CGSize)size borderColor:(UIColor *)color borderWidth:(CGFloat)borderWidth
{
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
[[UIColor clearColor] set];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
CGContextSetLineWidth(context, borderWidth);
CGContextSetStrokeColorWithColor(context, color.CGColor);
CGFloat lengths[] = { 3, 1 };
CGContextSetLineDash(context, 0, lengths, 1);
CGContextMoveToPoint(context, 0.0, 0.0);
CGContextAddLineToPoint(context, size.width, 0.0);
CGContextAddLineToPoint(context, size.width, size.height);
CGContextAddLineToPoint(context, 0, size.height);
CGContextAddLineToPoint(context, 0.0, 0.0);
CGContextStrokePath(context);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
9朵锣、禁止當前頁面的返回手勢
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// 禁用返回手勢
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
// 開啟返回手勢
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}
}
10谬盐、在 button 加載網絡圖片
// 1、單獨加載網絡圖片 可以用SDWebImage 下的 "UIButton+WebCache.h"
[btn sd_setImageWithURL:[NSURL URLWithString:model.imgurl] forState:UIControlStateNormal];
// 2诚些、加載網絡圖片和文字時·需要注意圖片的大小
/**
* 異步加載圖片
*/
[[SDImageCache sharedImageCache] storeImage:btn.imageView.image forKey:urlStr toDisk:NO];
[[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:urlStr] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
// 主線程刷新UI
dispatch_async(dispatch_get_main_queue(), ^{
CGSize imagesize; //需要圖片的大小
UIImage *smallImage = [self imageWithImage:image scaledToSize:imagesize];//裁剪
[btn setImage:smallImage forState:UIControlStateNormal];
[btn setTitle:name forState:UIControlStateNormal];
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
btn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
});
}];
11飞傀、button 按鈕圖片和文字(圖片左·文字右,文字隔圖片10px)
//當圖片過大時·文字可能顯示不出來·所以要把圖片壓縮成button一樣的高度·就可以顯示出來
[btn setImage:image forState:UIControlStateNormal];
[btn setTitle:name forState:UIControlStateNormal];
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
btn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
//button 折行顯示設置
/*
NSLineBreakByWordWrapping = 0, // Wrap at word boundaries, default
NSLineBreakByCharWrapping, // Wrap at character boundaries
NSLineBreakByClipping, // Simply clip 裁剪從前面到后面顯示多余的直接裁剪掉
文字過長 button寬度不夠時: 省略號顯示位置...
NSLineBreakByTruncatingHead, // Truncate at head of line: "...wxyz" 前面顯示
NSLineBreakByTruncatingTail, // Truncate at tail of line: "abcd..." 后面顯示
NSLineBreakByTruncatingMiddle // Truncate middle of line: "ab...yz" 中間顯示省略號
*/
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
// you probably want to center it
button.titleLabel.textAlignment = NSTextAlignmentCenter; // if you want to
button.layer.borderColor = [UIColor blackColor].CGColor;
button.layer.borderWidth = 1.0;
// underline Terms and condidtions
NSMutableAttributedString* tncString = [[NSMutableAttributedString alloc] initWithString:@"View Terms and Conditions"];
//設置下劃線...
/*
NSUnderlineStyleNone = 0x00, 無下劃線
NSUnderlineStyleSingle = 0x01, 單行下劃線
NSUnderlineStyleThick NS_ENUM_AVAILABLE(10_0, 7_0) = 0x02, 粗的下劃線
NSUnderlineStyleDouble NS_ENUM_AVAILABLE(10_0, 7_0) = 0x09, 雙下劃線
*/
[tncString addAttribute:NSUnderlineStyleAttributeName
value:@(NSUnderlineStyleSingle)
range:(NSRange){0,[tncString length]}];
//此時如果設置字體顏色要這樣
[tncString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,[tncString length])];
//設置下劃線顏色...
[tncString addAttribute:NSUnderlineColorAttributeName value:[UIColor redColor] range:(NSRange){0,[tncString length]}];
[button setAttributedTitle:tncString forState:UIControlStateNormal];
12诬烹、在xib(storyboard)中使用 UIScrollView, 默認是勾選了autolayout選項的砸烦,在autolayout下,iOS計算UIScrollView的contentsize的機制
- iOS7中,需在viewDidLayoutSubviews中設置scrollView.contentSize屬性
-(void)viewDidLayoutSubviews
{
self.scrollView.contentSize = CGSizeMake(xx,xx);
}
- iOS8及以上绞吁,只需要在viewDidAppear方法中設置就好了
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
self.scrollView.contentSize = CGSizeMake(xx,xx);
}
所以幢痘,如果要最低支持iOS7系統(tǒng),只需在viewDidLayoutSubviews中設置contentSize屬性即可家破。
13颜说、刷新框架的適配iOS11
- 如果你使用了MJRefresh等刷新购岗,并且你還隱藏了導航
if (@available(iOS 11.0, *)) {
self.tableview.contentInsetAdjustmentBehavior = UIApplicationBackgroundFetchIntervalNever;
} else {
self.automaticallyAdjustsScrollViewInsets = false;
}
//代碼適配iOS11
#define naviBarH ([[UIApplication sharedApplication] statusBarFrame].size.height + 44)
#define tabBarH ([[UIApplication sharedApplication] statusBarFrame].size.height>20?83:49)
#define AboveIOS9 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)
// iPhone X 尺寸 375*812
#define XY_iPhoneX (IS_IPHONE && XY_ScreenWidth == 375.f && XY_ScreenHeight == 812.f)
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define SafeAreaBottomHeight (kWJScreenHeight == 812.0 ? 34 : 0)
//iOS11 刷新單個cell或者刷新一組cell 的時候需要用到,不然會移動
_tableView.estimatedRowHeight = 0;
_tableView.estimatedSectionHeaderHeight = 0;
_tableView.estimatedSectionFooterHeight = 0;
//代碼適配安全區(qū)域
- (void)viewSafeAreaInsetsDidChange {
[super viewSafeAreaInsetsDidChange];
NSLog(@"viewSafeAreaInsetsDidChange-%@",NSStringFromUIEdgeInsets(self.view.safeAreaInsets));
[self updateOrientation];
}
- (void)updateOrientation {
if (@available(iOS 11.0, *)) {
CGRect frame = self.customerView.frame;
frame.origin.x = self.view.safeAreaInsets.left;
frame.size.width = self.view.frame.size.width - self.view.safeAreaInsets.left - self.view.safeAreaInsets.right;
frame.size.height = self.view.frame.size.height - self.view.safeAreaInsets.bottom;
self.customerView.frame = frame;
} else {
// Fallback on earlier versions
}
}
14门粪、xcode打印的位置喊积,方法,行數(shù)
#ifdef DEBUG
#if TARGET_IPHONE_SIMULATOR//模擬器
#define NSLog(...) NSLog(@"%s 第%d行 \n %@\n\n",__func__,__LINE__,[NSString stringWithFormat:__VA_ARGS__])
#elif TARGET_OS_IPHONE//真機
#define NSLog(...) NSLog(@"%s 第%d行 \n %@\n\n",__func__,__LINE__,[NSString stringWithFormat:__VA_ARGS__])
//#define NSLog(...) fprintf(stderr,"[%s-%d行] %s\n",[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, [[NSString stringWithFormat:@"%@", ##__VA_ARGS__] UTF8String]);
#endif
#else
//正式發(fā)布
#ifdef zhengShiFaBu
#define NSLog(...)
#else
#define NSLog(...) NSLog(__VA_ARGS__)
#endif
#endif
15庄拇、弱引用注服、強引用
#ifndef weakify
#if DEBUG
#if __has_feature(objc_arc)
#define weakify(object) autoreleasepool{} __weak __typeof__(object) weak##_##object = object;
#else
#define weakify(object) autoreleasepool{} __block __typeof__(object) block##_##object = object;
#endif
#else
#if __has_feature(objc_arc)
#define weakify(object) try{} @finally{} {} __weak __typeof__(object) weak##_##object = object;
#else
#define weakify(object) try{} @finally{} {} __block __typeof__(object) block##_##object = object;
#endif
#endif
#endif
#ifndef strongify
#if DEBUG
#if __has_feature(objc_arc)
#define strongify(object) autoreleasepool{} __typeof__(object) object = weak##_##object;
#else
#define strongify(object) autoreleasepool{} __typeof__(object) object = block##_##object;
#endif
#else
#if __has_feature(objc_arc)
#define strongify(object) try{} @finally{} __typeof__(object) object = weak##_##object;
#else
#define strongify(object) try{} @finally{} __typeof__(object) object = block##_##object;
#endif
#endif
#endif
16、UITableView
- xib 創(chuàng)建cell. 先注冊
[self.tableView registerNib:[UINib
nibWithNibName:NSStringFromClass([MyCell class])
bundle:nil]
forCellReuseIdentifier:ID];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
- sb 創(chuàng)建cell. 直接
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
17措近、根據(jù)UITableView點擊tableviewCell獲取在當前屏幕中的坐標值
CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];
CGRect rect = [tableView convertRect:rectInTableView toView:[tableView superview]];
18溶弟、UITableView 刷新
//一個section刷新
NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1]; //你需要更新的組數(shù)
[tableview reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic]; //collection 相同
//一個cell刷新
NSIndexPath *indexPath=[NSIndexPath indexPathForRow:3 inSection:0]; //你需要更新的組數(shù)中的cell
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone]; //collection 相同
19、UITableViewcell 鑲嵌 UITextField 復用的問題
- 因為cell每次滑動過程都是從緩存池中去取·所以需要建一個數(shù)據(jù)來保存
在cell里面用blokc把每次改變的值傳過去 然后保存起來
//1
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (block) {
block([textField.text stringByReplacingCharactersInRange:range withString:string]);
}
return YES;;
}
//2
cell. block = ^(NSString *title) {
[self.dataDic setObject:title forKey:@(indexPath.row)];
};
NSArray *arr = [self.dataDic allKeys];
if ([arr containsObject:@(indexPath.row)]) {
cell.textField.text = [self.dataDic objectForKey:@(indexPath.row)];
}else{
cell.textField.text = nil;
}
20瞭郑、手機屏幕一直亮著
[UIApplication sharedApplication].idleTimerDisabled = YES;
21辜御、UILabel的文字里面有特殊字符的時候(數(shù)字,空格等),會自動換行的問題
textLabel.lineBreakMode = NSLineBreakByCharWrapping;
// 文字和圖片混合排列
NSTextAttachment *attach = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
attach.image = [UIImage imageNamed:@"test"];
NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString:@"文字\uFFFC混合排列"];
[attrString addAttribute:NSAttachmentAttributeName value:attach range:NSMakeRange(0, attrString.length)];
_labeltest.attributedText = attrString;