转载地址:http://www.jianshu.com/p/9fcd37c0ea05
1、设置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;
// 或者使用xib,看下gif图
Untitled.gif
2、当使用-performSelector:withObject:withObject:afterDelay:方法时,需要传入多参数问题
3、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;
4、比较两个CGRect/CGSize/CGPoint是否相等
if (CGRectEqualToRect(rect1, rect2)) { // 两个区域相等
// do some
}
if (CGPointEqualToPoint(point1, point2)) { // 两个点相等 // do some } if (CGSizeEqualToSize(size1, size2)) { // 两个size相等 // do some }
5、比较两个NSDate相差多少小时
NSDate* date1 = someDate;
NSDate* date2 = someOtherDate;
NSTimeInterval distanceBetweenDates = [date1 timeIntervalSinceDate:date2];
double secondsInAnHour = 3600;
6、每个cell之间增加间距
7、播放一张张连续的图片
8、加载gif图片
推荐使用这个框架 FLAnimatedImage
9、防止离屏渲染为image添加圆角
10、查看系统所有字体
11、获取随机数
NSInteger i = arc4random();
12、获取随机数小数(0-1之间)
#define ARC4RANDOM_MAX 0x100000000
double val = ((double)arc4random() / ARC4RANDOM_MAX);
13、AVPlayer视频播放完成的通知监听
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(videoPlayEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
14、判断两个rect是否有交叉
if
15、判断一个字符串是否为数字
NSCharacterSet *notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([str rangeOfCharacterFromSet:notDigits].location == NSNotFound)
{
16、将一个view保存为pdf格式
- (
void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
NSMutableData *pdfData = [NSMutableData data]; UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil); UIGraphicsBeginPDFPage(); CGContextRef pdfContext = UIGraphicsGetCurrentContext(); [aView.layer renderInContext:pdfContext]; UIGraphicsEndPDFContext(); NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES); NSString* documentDirectory = [documentDirectories objectAtIndex:0]; NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename]; [pdfData writeToFile:documentDirectoryFilename atomically:YES]; NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename); }
17、让一个view在父视图中心
child.center =
[parent convertPoint:parent.center fromView:parent.superview];
18、获取当前导航控制器下前一个控制器
- (
UIViewController *)backViewController
{
NSInteger myIndex = [self.navigationController.viewControllers indexOfObject:self];
if ( myIndex != 0 && myIndex != NSNotFound ) { return [self.navigationController.viewControllers objectAtIndex:myIndex-1]; } else { return nil; } }
19、保存UIImage到本地
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"]; [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
20、键盘上方增加工具栏
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;
21、copy一个view
因为UIView没有实现copy协议,因此找不到copyWithZone方法,使用copy的时候导致崩溃但是我们可以通过归档再解档实现copy,这相当于对视图进行了一次深拷贝,代码如下
id copyOfView =
[NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:originalView]];
22、在image上绘制文字并生成新的image
UIFont *font = [UIFont boldSystemFontOfSize:
12];
UIGraphicsBeginImageContext(image.size);
[image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)]; CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height); [[UIColor whiteColor] set]; [text drawInRect:CGRectIntegral(rect) withFont:font]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
23、判断一个view是否为另一个view的子视图
24、判断一个字符串是否包含另一个字符串
25、UICollectionView自动滚动到某行
26、修改系统UIAlertController
27、判断某一行的cell是否已经显示
CGRect cellRect = [tableView rectForRowAtIndexPath:indexPath];
BOOL completelyVisible = CGRectContainsRect(tableView.bounds, cellRect);
28、让导航控制器pop回指定的控制器
NSMutableArray *allViewControllers = [NSMutableArray arrayWithArray:[self.navigationController viewControllers]];
for (UIViewController *aViewController in allViewControllers) { if ([aViewController isKindOfClass:[RequiredViewController class]]) { [self.navigationController popToViewController:aViewController animated:NO]; } }
29、动画修改label上的文字
30、判断字典中是否包含某个key值
if ([dic objectForKey:@"yourKey"]) {
NSLog(@"有这个值"); } else { NSLog(@"没有这个值"); }
31、获取屏幕方向
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if(orientation == 0)
32、设置UIImage的透明度
33、Attempt to mutate immutable object with insertString:atIndex:
这个错是因为你拿字符串调用insertString:atIndex:方法的时候,调用对象不是NSMutableString,应该先转成这个类型再调用
34、UIWebView添加单击手势不响应
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(webViewClick)];
tap.delegate = self; [_webView addGestureRecognizer:tap];
35、获取手机RAM容量
36、地图上两个点之间的实际距离
37、在应用中打开设置的某个界面
38、在UITextView中显示html文本
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 30, 100, 199)]; textView.backgroundColor = [UIColor redColor]; [self.view addSubview:textView]; NSString *htmlString = @"<h1>Header</h1><h2>Subheader</h2><p>Some <em>text</em></p>"; NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes: nil error: nil]; textView.attributedText = attributedString;
39、监听scrollView是否滚动到了顶部/底部
-(
void)scrollViewDidScroll: (UIScrollView*)scrollView
{
float scrollViewHeight = scrollView.frame.size.height;
float scrollContentSizeHeight = scrollView.contentSize.height; float scrollOffset = scrollView.contentOffset.y; if (scrollOffset == 0) {
40、UISlider增量/减量为固定值(假如为5)
- (
void)setupSlider
{
UISlider *slider = [[UISlider alloc] init];
[self.view addSubview:slider];
[slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged]; slider.maximumValue = 100; slider.minimumValue = 0; slider.frame = CGRectMake(200, 20, 100, 30); } - (void)sliderAction:(UISlider *)slider { [slider setValue:((int)((slider.value + 2.5) / 5) * 5) animated:NO]; }
41、选中textField或者textView所有文本(我这里以textView为例)
[self
.textView setSelectedTextRange:[self.textView textRangeFromPosition:self.textView.beginningOfDocument toPosition:self.textView.endOfDocument]]
42、从导航控制器中删除某个控制器
43、隐藏UITextView/UITextField光标
textField.tintColor = [UIColor clearColor]
44、当UITextView/UITextField中没有文字时,禁用回车键
textField.enablesReturnKeyAutomatically = YES
45、字符串encode编码(编码url字符串不成功的问题)
46、计算UILabel上某段文字的frame
@implementation UILabel (TextRect)
- (CGRect)boundingRectForCharacterRange:(NSRange)range { NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:[self attributedText]]; NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init]; [textStorage addLayoutManager:layoutManager]; NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:[self bounds].size]; textContainer.lineFragmentPadding = 0; [layoutManager addTextContainer:textContainer]; NSRange glyphRange; [layoutManager characterRangeForGlyphRange:range actualGlyphRange:&glyphRange]; return [layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textContainer]; }
47、获取随机UUID
NSString *result;
if([[[UIDevice currentDevice] systemVersion] floatValue] > 6.0)
{
result = [[NSUUID UUID] UUIDString]; } else { CFUUIDRef uuidRef = CFUUIDCreate(NULL); CFStringRef uuid = CFUUIDCreateString(NULL, uuidRef); CFRelease(uuidRef); result = (__bridge_transfer NSString *)uuid; }
48、仿苹果抖动动画
#define RADIANS(degrees) (((degrees) * M_PI) / 180.0)
- (void)startAnimate {
view.transform = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(-5)); [UIView animateWithDuration:0.25 delay:0.0 options:(UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse) animations:^ { view.transform = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(5)); } completion:nil]; } - (void)stopAnimate { [UIView animateWithDuration:0.25 delay:0.0 options:(UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear) animations:^ { view.transform = CGAffineTransformIdentity; } completion:nil]; }
49、修改UISearBar内部背景颜色
UITextField *textField = [_searchBar valueForKey:@
"_searchField"]
50、UITextView滚动到顶部
51、通知监听APP生命周期
UIApplicationDidEnterBackgroundNotification 应用程序进入后台UIApplicationWillEnterForegroundNotification 应用程序将要进入前台UIApplicationDidFinishLaunchingNotification 应用程序完成启动UIApplicationDidFinishLaunchingNotification 应用程序由挂起变的活跃UIApplicationWillResignActiveNotification 应用程序挂起(有电话进来或者锁屏)UIApplicationDidReceiveMemoryWarningNotification 应用程序收到内存警告UIApplicationDidReceiveMemoryWarningNotification 应用程序终止(后台杀死、手机关机等)UIApplicationSignificantTimeChangeNotification 当有重大时间改变(凌晨0点,设备时间被修改,时区改变等)UIApplicationWillChangeStatusBarOrientationNotification 设备方向将要改变UIApplicationDidChangeStatusBarOrientationNotification 设备方向改变UIApplicationWillChangeStatusBarFrameNotification 设备状态栏frame将要改变UIApplicationDidChangeStatusBarFrameNotification 设备状态栏frame改变UIApplicationBackgroundRefreshStatusDidChangeNotification 应用程序在后台下载内容的状态发生变化UIApplicationProtectedDataWillBecomeUnavailable 本地受保护的文件被锁定,无法访问UIApplicationProtectedDataWillBecomeUnavailable 本地受保护的文件可用了
52、触摸事件类型
UIControlEventTouchCancel 取消控件当前触发的事件UIControlEventTouchDown 点按下去的事件UIControlEventTouchDownRepeat 重复的触动事件UIControlEventTouchDragEnter 手指被拖动到控件的边界的事件UIControlEventTouchDragExit 一个手指从控件内拖到外界的事件UIControlEventTouchDragInside 手指在控件的边界内拖动的事件UIControlEventTouchDragOutside 手指在控件边界之外被拖动的事件UIControlEventTouchUpInside 手指处于控制范围内的触摸事件UIControlEventTouchUpOutside 手指超出控制范围的控制中的触摸事件
53、UITextField文字周围增加边距
54、监听UISlider拖动状态
55、设置UITextField光标位置
56、去除webView底部黑色
[webView setBackgroundColor:[
UIColor clearColor]];
[webView setOpaque:NO];
for (UIView *v1 in [webView subviews]) { if ([v1 isKindOfClass:[UIScrollView class]]) { for (UIView *v2 in v1.subviews) { if ([v2 isKindOfClass:[UIImageView class]]) { v2.hidden = YES; } } } }
57、获取collectionViewCell在屏幕中的frame
UICollectionViewLayoutAttributes *attributes = [collectionView
layoutAttributesForItemAtIndexPath:indexPath];
CGRect cellRect = attributes.frame;
CGRect cellFrameInSuperview = [collectionView convertRect:cellRect toView:[cv superview]];
58、比较两个UIImage是否相等
- (
BOOL)image:(UIImage *)image1 isEqualTo:(UIImage *)image2
{
NSData *data1 = UIImagePNGRepresentation(image1); NSData *data2 = UIImagePNGRepresentation(image2); return [data1 isEqual:data2]; }
59、解决当UIScrollView上有UIButton的时候,触摸到button滑动不了的问题
60、UITextView中的文字添加阴影效果
- (void)setTextLayer:(UITextView *)textView color:(UIColor *)color
{
CALayer *textLayer = ((CALayer *)[textView.layer.
sublayers objectAtIndex:0])
61、MD5加密
+ (
NSString *)md5:(NSString *)str
{
const char *concat_str = [str UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH]; CC_MD5(concat_str, (unsigned int)strlen(concat_str), result); NSMutableString *hash = [NSMutableString string]; for (int i =0; i <16; i++){ [hash appendFormat:@"X", result[i]]; } return [hash uppercaseString]; }
62、base64加密
@
interface NSData (Base64)
/**
* @brief 字符串base64后转data
*/
+ (NSData *)dataWithBase64EncodedString:(NSString *)string { if (![string length]) return nil; NSData *decoded = nil;
63、AES加密
#import <CommonCrypto/CommonCryptor.h>
@interface NSData (AES)
64、3DES加密
#import <CommonCrypto/CommonCryptor.h>
@interface NSData (3DES)
65、单个页面多个网络请求的情况,需要监听所有网络请求结束后刷新UI
dispatch_group_t group = dispatch_group_create()
66、解决openUrl延时问题
67、页面跳转实现翻转动画
68、tableView实现无限滚动
- (
void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat actualPosition = scrollView.contentOffset.y;
CGFloat contentHeight = scrollView.contentSize.height - scrollView.frame.size.height;
if (actualPosition >= contentHeight) { [self.dataArr addObjectsFromArray:self.dataArr]; [self.tableView reloadData]; } }
69、代码方式调整屏幕亮度
70、获取当前应用CUP用量
float cpu_usage() { kern_return_t kr; task_info_data_t tinfo; mach_msg_type_number_t task_info_count; task_info_count = TASK_INFO_MAX; kr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count); if (kr != KERN_SUCCESS) { return -1; } task_basic_info_t basic_info; thread_array_t thread_list; mach_msg_type_number_t thread_count; thread_info_data_t thinfo; mach_msg_type_number_t thread_info_count; thread_basic_info_t basic_info_th; uint32_t stat_thread = 0;
71、float数据取整四舍五入
CGFloat f =
4.65
72、删除UISearchBar系统默认边框
73、为UICollectionViewCell设置圆角和阴影
cell.contentView.layer.cornerRadius =
2.0f
74、让正在滑动的scrollView停止滚动(不是禁止,而是暂时停止滚动)
[
scrollView setContentOffset:scrollView.contentOffset animated:NO]
75、使用xib设置UIView的边框、圆角
圆角和边框看下图即可设置
xib设置圆角边框.png
但是增加layer.borderColor的keyPath设置边框颜色并不能起作用,后来查了资料,这里应该用layer.borderUIColor,但是这里设置的颜色不起作用,无论设置什么颜色显示出来的都是黑色的。后来又去查了下,有种解决方案是给CALayer添加一个分类,提供一个 - (void)setBorderUIColor:(UIColor *)color;方法就可以解决了,实现如下:
xib设置边框颜色.png
#import "CALayer+BorderColor.h"
@implementation CALayer (BorderColor) - (void)setBorderUIColor:(UIColor *)color { self.borderColor = color.CGColor; }
76、根据经纬度获取城市等信息
77、如何防止添加多个NSNotification观察者?
78、将一个xib添加到另外一个xib上
将一个xib添加到另外一个xib上.png
79、处理字符串,使其首字母大写
NSString *
str =
80、判断一个UIAlertView/UIAlertController是否显示
81、获取字符串中的数字
- (
NSString *)getNumberFromStr:(NSString *)str
{
NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
return [[str componentsSeparatedByCharactersInSet:nonDigitCharacterSet] componentsJoinedByString:@""]; } NSLog(@"%@", [self getNumberFromStr:@"a0b0c1d2e3f4fda8fa8fad9fsad23"]);
82、为UIView的某个方向添加边框
83、通过属性设置UISwitch、UIProgressView等控件的宽高
mySwitch.transform = CGAffineTransformMakeScale(5.0f, 5.0f);
progressView.transform = CGAffineTransformMakeScale(5.0f, 5.0f);
84、自动搜索功能,用户连续输入的时候不搜索,用户停止输入的时候自动搜索(我这里设置的是0.5s,可根据需求更改)
85、修改UISearchBar的占位文字颜色
86、某个界面多个事件同时响应引起的问题(比如,两个button同时按push到新界面,两个都会响应,可能导致push重叠)
87、修改tabBar的frame
88、修改键盘背景颜色
89、修改image颜色
UIImage *image = [UIImage imageNamed:@"test"];
imageView.image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height); UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextClipToMask(context, rect, image.CGImage); CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]); CGContextFillRect(context, rect); UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); UIImage *flippedImage = [UIImage imageWithCGImage:img.CGImage scale:1.0 orientation: UIImageOrientationDownMirrored]; imageView.image = flippedImage;
90、动画执行removeFromSuperview
[UIView animateWithDuration:0.2
animations:
91、设置UIButton高亮背景颜色
[UIView animateWithDuration:0.2
animations:
92、设置UIButton高亮时的背景颜色
93、关于图片拉伸
推荐看这个博客,讲的很详细http://blog.csdn.net/q199109106q/article/details/8615661
94、利用runtime获取一个类所有属性
- (
NSArray *)allPropertyNames:(Class)aClass
{
unsigned count;
objc_property_t *properties = class_copyPropertyList(aClass, &count)
95、设置textView的某段文字变成其他颜色
- (void)setupTextView:(UITextView *)textView
text:(NSString *)text color:(UIColor *)color {
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:textView.text]; [string addAttribute:NSForegroundColorAttributeName value:color range:[textView.text rangeOfString:text]]; [textView setAttributedText:string]; }
96、让push跳转动画像modal跳转动画那样效果(从下往上推上来)
- (void)push
{
TestViewController *vc = [[TestViewController alloc] init]
97、上传图片太大,压缩图片
-(UIImage *)resizeImage:(UIImage *)
image
{
float actualHeight = image.size.height; float actualWidth = image.size.width; float maxHeight = 300.0; float maxWidth = 400.0; float imgRatio = actualWidth/actualHeight; float maxRatio = maxWidth/maxHeight; float compressionQuality = 0.5;
转载于:https://www.cnblogs.com/lujianwenance/p/7154332.html
相关资源:各显卡算力对照表!