本文主要记录一些常用知识点:
一:UILabel处理
- 设置UILabel行间距
NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString:label.text];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:20];
[attrString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, label.text.length)];
label.attributedText = attrString;
- UILabel显示不同颜色字体
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:label.text];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];
label.attributedText = string;
二:比较两个CGRect/CGSize/CGPoint是否相等
if (CGRectEqualToRect(rect1, rect2)) { // 两个区域相等
// do some
}
if (CGPointEqualToPoint(point1, point2)) { // 两个点相等
// do some
}
if (CGSizeEqualToSize(size1, size2)) { // 两个size相等
// do some
}
三:比较两个NSDate相差多少小时
NSDate* date1 = someDate;
NSDate* date2 = someOtherDate;
NSTimeInterval distanceBetweenDates = [date1 timeIntervalSinceDate:date2];
double secondsInAnHour = 3600;
// 除以3600是把秒化成小时,除以60得到结果为相差的分钟数
NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;
四:每个cell之间增加间距
- 方法一,每个分区只显示一行cell,分区头当作你想要的间距(注意,从数据源数组中取值的时候需要用
indexPath.section
而不是indexPath.row
) - 方法二,自定义cell,重写setFrame:
- (void)setFrame:(CGRect)frame
{
frame.size.height -= 20;
[super setFrame:frame];
}
五:播放一张张连续的图片
加入现在有三张图片分别为animate_1、animate_2、animate_3
- 方法一
imageView.animationImages = @[[UIImage imageNamed:@"animate_1"], [UIImage imageNamed:@"animate_2"], [UIImage imageNamed:@"animate_3"]];
imageView.animationDuration = 1.0;
- 方法二
imageView.image = [UIImage animatedImageNamed:@"animate_" duration:1.0];
// 方法二解释下,这个方法会加载animate_为前缀的,后边0-1024,也就是animate_0、animate_1一直到animate_1024
六:防止离屏渲染为image添加圆角
// image分类
- (UIImage *)circleImage
{
// NO代表透明
UIGraphicsBeginImageContextWithOptions(self.size, NO, 1);
// 获得上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 添加一个圆
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
// 方形变圆形
CGContextAddEllipseInRect(ctx, rect);
// 裁剪
CGContextClip(ctx);
// 将图片画上去
[self drawInRect:rect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
七:键盘上方增加工具栏
UIToolbar *keyboardDoneButtonView = [[UIToolbar alloc] init];
[keyboardDoneButtonView sizeToFit];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonItemStyleBordered target:self
action:@selector(doneClicked:)];
[keyboardDoneButtonView setItems:[NSArray arrayWithObjects:doneButton, nil]];
txtField.inputAccessoryView = keyboardDoneButtonView;
八:判断某一行的cell是否已经显示
CGRect cellRect = [tableView rectForRowAtIndexPath:indexPath];
BOOL completelyVisible = CGRectContainsRect(tableView.bounds, cellRect);
九:让导航控制器pop回指定的控制器
NSMutableArray *allViewControllers = [NSMutableArray arrayWithArray:[self.navigationController viewControllers]];
for (UIViewController *aViewController in allViewControllers) {
if ([aViewController isKindOfClass:[RequiredViewController class]]) {
[self.navigationController popToViewController:aViewController animated:NO];
}
}
十:获取屏幕方向
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if(orientation == 0) //Default orientation
//默认
else if(orientation == UIInterfaceOrientationPortrait)
//竖屏
else if(orientation == UIInterfaceOrientationLandscapeLeft)
// 左横屏
else if(orientation == UIInterfaceOrientationLandscapeRight)
//右横屏
十一:UIWebView添加单击手势不响应
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(webViewClick)];
tap.delegate = self;
[_webView addGestureRecognizer:tap];
// 因为webView本身有一个单击手势,所以再添加会造成手势冲突,从而不响应。需要绑定手势代理,并实现下边的代理方法
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
return YES;
}
十二:获取手机RAM容量
// 需要导入#import
mach_port_t host_port;
mach_msg_type_number_t host_size;
vm_size_t pagesize;
host_port = mach_host_self();
host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
host_page_size(host_port, &pagesize);
vm_statistics_data_t vm_stat;
if (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size) != KERN_SUCCESS) {
NSLog(@"Failed to fetch vm statistics");
}
/* Stats in bytes */
natural_t mem_used = (vm_stat.active_count +
vm_stat.inactive_count +
vm_stat.wire_count) * pagesize;
natural_t mem_free = vm_stat.free_count * pagesize;
natural_t mem_total = mem_used + mem_free;
NSLog(@"已用: %u 可用: %u 总共: %u", mem_used, mem_free, mem_total);
十三:当UITextView/UITextField中没有文字时,禁用回车键
textField.enablesReturnKeyAutomatically = YES;
十四:UISearchBar
- 修改UISearBar内部背景颜色
UITextField *textField = [_searchBar valueForKey:@"_searchField"];
textField.backgroundColor = [UIColor redColor];
- 修改UISearchBar的占位文字颜色
UITextField *searchField = [searchBar valueForKey:@"_searchField"];
[searchField setValue:[UIColor blueColor] forKeyPath:@"_placeholderLabel.textColor"];
- 用户停止输入的时候自动搜索
// 输入框文字改变的时候调用
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
// 先取消调用搜索方法
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(searchNewResult) object:nil];
// 0.5秒后调用搜索方法
[self performSelector:@selector(searchNewResult) withObject:nil afterDelay:0.5];
}
- 删除UISearchBar系统默认边框
// 方法一
searchBar.searchBarStyle = UISearchBarStyleMinimal;
// 方法二
[searchBar setBackgroundImage:[[UIImage alloc]init]];
// 方法三
searchBar.barTintColor = [UIColor whiteColor];
十五:触摸事件类型
UIControlEventTouchCancel 取消控件当前触发的事件
UIControlEventTouchDown 点按下去的事件
UIControlEventTouchDownRepeat 重复的触动事件
UIControlEventTouchDragEnter 手指被拖动到控件的边界的事件
UIControlEventTouchDragExit 一个手指从控件内拖到外界的事件
UIControlEventTouchDragInside 手指在控件的边界内拖动的事件
UIControlEventTouchDragOutside 手指在控件边界之外被拖动的事件
UIControlEventTouchUpInside 手指处于控制范围内的触摸事件
UIControlEventTouchUpOutside 手指超出控制范围的控制中的触摸事件
十六:多个网络请求的情况,需要监听所有网络请求结束后刷新UI
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t serialQueue = dispatch_queue_create("com.wzb.test.www", DISPATCH_QUEUE_SERIAL);
dispatch_group_enter(group);
dispatch_group_async(group, serialQueue, ^{
// 网络请求一
[WebClick getDataSuccess:^(ResponseModel *model) {
dispatch_group_leave(group);
} failure:^(NSString *err) {
dispatch_group_leave(group);
}];
});
dispatch_group_enter(group);
dispatch_group_async(group, serialQueue, ^{
// 网络请求二
[WebClick getDataSuccess:getBigTypeRM onSuccess:^(ResponseModel *model) {
dispatch_group_leave(group);
} failure:^(NSString *errorString) {
dispatch_group_leave(group);
}];
});
dispatch_group_enter(group);
dispatch_group_async(group, serialQueue, ^{
// 网络请求三
[WebClick getDataSuccess:^{
dispatch_group_leave(group);
} failure:^(NSString *errorString) {
dispatch_group_leave(group);
}];
});
// 所有网络请求结束后会来到这个方法
dispatch_group_notify(group, serialQueue, ^{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
// 刷新UI
});
});
});
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{ /*任务a */ });
dispatch_group_async(group, queue, ^{ /*任务b */ });
dispatch_group_async(group, queue, ^{ /*任务c */ });
dispatch_group_async(group, queue, ^{ /*任务d */ });
dispatch_group_notify(group,dispatch_get_main_queue(), ^{
// 在a、b、c、d异步执行完成后,会回调这里
});
十七:单例模式宏
大神们把单例模式的各种套路封装成了宏。这样使用的时候,就不需要每个类都手动写一遍里面的重复代码了。省去了敲代码的时间。
#define DJ_SINGLETON_DEF(_type_) + (_type_ *)sharedInstance;\
+(instancetype) alloc __attribute__((unavailable("call sharedInstance instead")));\
+(instancetype) new __attribute__((unavailable("call sharedInstance instead")));\
-(instancetype) copy __attribute__((unavailable("call sharedInstance instead")));\
-(instancetype) mutableCopy __attribute__((unavailable("call sharedInstance instead")));\
#define DJ_SINGLETON_IMP(_type_) + (_type_ *)sharedInstance{\
static _type_ *theSharedInstance = nil;\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
theSharedInstance = [[super alloc] init];\
});\
return theSharedInstance;\
}
那么,在定义和实现的时候就很简单了:
@interface DJSingleton : NSObject
DJ_SINGLETON_DEF(DJSingleton);
@end
@implementation DJSingleton
DJ_SINGLETON_IMP(DJSingleton);
@end
十八:给UIImage添加生成圆角图片的扩展API
- (UIImage *)imageWithCornerRadius:(CGFloat)radius {
CGRect rect = (CGRect){0.f, 0.f, self.size};
UIGraphicsBeginImageContextWithOptions(self.size, NO, UIScreen.mainScreen.scale);
CGContextAddPath(UIGraphicsGetCurrentContext(),
[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius].CGPath);
CGContextClip(UIGraphicsGetCurrentContext());
[self drawInRect:rect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
这车怎么样?
待续。。。