1. Don’t sleep on your phone
[UIApplication sharedApplication].idleTimerDisabled = YES;
Copy the code
2. Hide a cell line
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {// if it is the row you need to hide, If (indexPath. Row == YouWantToHideRow) return 0; return 44; } // Then call [self.tableView beginUpdates] when you need to hide the cell; [self.tableView endUpdates];Copy the code
3. Disable Button highlighting
button.adjustsImageWhenHighlighted = NO; Or when creating a UIButton * button = [UIButton buttonWithType: UIButtonTypeCustom];Copy the code
4, Failed to obtain a cell from its dataSource
Your cell was called too early. The cell is first recycled and then created. Possible causes are as follows: 1. The xiB cell is not registered; 2. This cell is already cached in the memory (that is, the cell found through your cellId is not the type you want)
Cocoa Pods reported this error: Unable to access ‘Github.com/facebook/po…: Operation timed out after 0 milliseconds with 0 out of 0 bytes received
Solution: The cause may be a network problem. The network request timed out. You only need to retry
Cocoa Pods ERROR: While Executing gem… (Errno::EPERM)
Solution: https://segmentfault.com/q/1010000002926243
7. Animate the window root controller
// options are animation options [UIView transitionWithView:[UIApplication sharedApplication]. KeyWindow Duration: 0.5F options:UIViewAnimationOptionTransitionCrossDissolve animations:^{ BOOL oldState = [UIView areAnimationsEnabled]; [UIView setAnimationsEnabled:NO]; [UIApplication sharedApplication].keyWindow.rootViewController = [RootViewController new]; [UIView setAnimationsEnabled:oldState]; } completion:^(BOOL finished) { }];Copy the code
Remove duplicate objects from the array
NSArray * newArr = [oldArr valueForKeyPath: @ "@ distinctUnionOfObjects. Self"];Copy the code
9. Encountered during compilationNo such file or directory: / users/apple/XXX
Because the compile time, the file is not found under this path, to solve this problem, the first is to check if missing files in the project, if not in the engineering, needs from the local drag in, if it is found that already exist in engineering, or drag in or error, at this moment need to build phases in search the file, In this case, it is likely to search for two identical files, in this case, one path is correct, delete the other can be. If that still doesn’t work, delete both and drag the file back into the project
10, iOS8 system, tableView is best implemented under -tableView: heightForRowAtIndexPath: this proxy method, or in iOS8 may appear incomplete display or unable to respond to the event problem
11, iOS8 to achieve the sideslip function when this method must be implemented, or in iOS8 can not sideslip
/ / must write method, and use editActionsForRowAtIndexPath pairing, What don't write all right - (void) inside tableView: (UITableView *) tableView commitEditingStyle: (editingStyle UITableViewCellEditingStyle) forRowAtIndexPath:(NSIndexPath *)indexPath { }Copy the code
12. Three notices
NSSystemTimeZoneDidChangeNotification listening modification time interface of two buttons UIApplicationSignificantTimeChangeNotification state changes to monitor users to change the time (just click on Settings button is invoked automatically) NSSystemClockDidChangeNotification monitor user modification time (time different will call)
13. SDWebImage local caching can sometimes be harmful. If you have cached an image before, even if the server changes the image next time but the IMAGE URL is not changed, the image downloaded with sdWebImage will still be the same as before. Therefore, if you encounter this problem, do not first depress the server, just clear the cache and try again.
14. Note before going online:
1) delete all the test codes in the code 2), if there is a background audit mode, remind the background to open this mode 3), the main process run again 4), global search waring, check all marked waring places
15. Jump into app permission Settings
/ / into the app Settings if (UIApplicationOpenSettingsURLString! = NULL) { UIApplication *application = [UIApplication sharedApplication]; NSURL *URL = [NSURL URLWithString:UIApplicationOpenSettingsURLString]; if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) { [application openURL:URL options:@{} completionHandler:nil]; } else { [application openURL:URL]; }}Copy the code
16. Take a screenshot of the view
UIGraphicsBeginImageContextWithOptions (view. Bounds. The size, YES, 0.0); [view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();Copy the code
17, if you want to dynamically modify the tableView tableHeaderView or tableFooterView height, need to reset the tableView, rather than directly change the height. The right thing to do is to reset the tableView. TableFooterView = changed the height of the view. Why is that? In fact, iOS8 above directly change the height is no problem, in iOS8 there is a problem with contentSize is not accurate, this is the solution.
18. Note that when an object is nil, the method that calls this object class does not execute
19, The content of the collectionView is not allowed to scroll when it is smaller than its width and height.
collectionView.alwaysBounceHorizontal = YES;
collectionView.alwaysBounceVertical = YES;
Copy the code
20, Set the title color and size on the navigationBar
[self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor youColor], NSFontAttributeName : [UIFont systemFontOfSize:15]}]
Copy the code
21, color to picture
+ (UIImage *)cl_imageWithColor:(UIColor *)color {CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f); UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }Copy the code
22, View set rounded corners
#define ViewBorderRadius(View, Radius, Width, Color)\ \ [View.layer setCornerRadius:(Radius)]; \ [View.layer setMasksToBounds:YES]; \ [View.layer setBorderWidth:(Width)]; \ [view. layer setBorderColor:[Color CGColor]] // View rounded cornersCopy the code
23. Strong/weak references
#define WeakSelf(type) __weak typeof(type) weak##type = type; // weak
#define StrongSelf(type) __strong typeof(type) type = weak##type; // strong
Copy the code
Convert radians from Angle
#define DegreesToRadian(x) (M_PI * (x) / 180Copy the code
25. Convert the Angle from radians
# define RadianToDegrees (radian) (radian * 180.0)/(M_PI)Copy the code
26. Access image resources
#define GetImage(imageName) [UIImage imageNamed:[NSString stringWithFormat:@"%@",imageName]]
Copy the code
27. Obtain temp
#define PathTemp NSTemporaryDirectory()
Copy the code
28, get sandbox Document
#define PathDocument [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
Copy the code
29. Obtain the sandbox Cache
#define PathCache [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]
Copy the code
30. GCD code is executed only once
#define kDISPATCH_ONCE_BLOCK(onceBlock) static dispatch_once_t onceToken; dispatch_once(&onceToken, onceBlock);
Copy the code
31. Customize NSLog
#ifdef DEBUG
#define NSLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#define NSLog(...)
#endif
Copy the code
32, the Font
#define FontL(s) [UIFont systemFontOfSize:s weight:UIFontWeightLight]
#define FontR(s) [UIFont systemFontOfSize:s weight:UIFontWeightRegular]
#define FontB(s) [UIFont systemFontOfSize:s weight:UIFontWeightBold]
#define FontT(s) [UIFont systemFontOfSize:s weight:UIFontWeightThin]
#define Font(s) FontL(s)
Copy the code
33 and the FORMAT
#define FORMAT(f, ...) [NSString stringWithFormat:f, ## __VA_ARGS__]
Copy the code
34. Run on the main thread
#define kDISPATCH_MAIN_THREAD(mainQueueBlock) dispatch_async(dispatch_get_main_queue(), mainQueueBlock);
Copy the code
35. Enable asynchronous threads
#define kDISPATCH_GLOBAL_QUEUE_DEFAULT(globalQueueBlock) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), globalQueueBlocl);
Copy the code
36, notifications,
#define NOTIF_ADD(n, f) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(f) name:n object:nil] #define NOTIF_POST(n, o) [[NSNotificationCenter defaultCenter] postNotificationName:n object:o] #define NOTIF_REMV() [[NSNotificationCenter defaultCenter] removeObserver:self]Copy the code
37. Random colors
+ (UIColor *)RandomColor { NSInteger aRedValue = arc4random() % 255; NSInteger aGreenValue = arc4random() % 255; NSInteger aBlueValue = arc4random() % 255; UIColor *randColor = [UIColor colorWithRed:aRedValue / 255.0f Green :aGreenValue / 255.0F Blue :aBlueValue / 255.0F Alpha: 1.0 f]; return randColor; }Copy the code
38, Get window
+(UIWindow*)getWindow { UIWindow* win = nil; //[UIApplication sharedApplication].keyWindow; for (id item in [UIApplication sharedApplication].windows) { if ([item class] == [UIWindow class]) { if (! ((UIWindow*)item).hidden) { win = item; break; } } } return win; }Copy the code
39. Modify textField placeholder font color and size
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
Copy the code
Put away the keyboard
[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
Copy the code
Control screen rotation, write in the controller
/** support automatic screen rotation */ - (BOOL)shouldAutorotate {return YES; } / what screen direction * / * * support - (UIInterfaceOrientationMask) supportedInterfaceOrientations {return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight; } /** Default screen orientation (the current ViewController must be modally rendered by UIViewController (modally rendered with navigation invalid), Will call this method) * / - (UIInterfaceOrientation) preferredInterfaceOrientationForPresentation {return UIInterfaceOrientationLandscapeLeft | UIInterfaceOrientationLandscapeRight; }Copy the code
42. Get app cache size
- (CGFloat)getCachSize { NSUInteger imageCacheSize = [[SDImageCache sharedImageCache] getSize]; // Get a custom cache size // walk through the contents of a folder with an enumerator //1. Access to the folder the enumerator nsstrings * myCachePath = [NSHomeDirectory () stringByAppendingPathComponent: @ "Library/Caches"]. NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:myCachePath]; __block NSUInteger count = 0; / / 2. Traversal for (nsstrings * fileName in enumerator) {nsstrings * path = [myCachePath stringByAppendingPathComponent: fileName]; NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil]; count += fileDict.fileSize; CGFloat totalSize = ((CGFloat)imageCacheSize+count)/1024/1024; return totalSize; }Copy the code
43. Clear the APP cache
- (void)handleClearView {// Remove two parts //1. [[SDImageCache sharedImageCache] clearMemory]; // Clear the disk cache [[SDImageCache sharedImageCache] clearDisk]; / / 2. Delete your cache nsstrings * myCachePath = [NSHomeDirectory () stringByAppendingPathComponent: @ "Library/Caches"]. [[NSFileManager defaultManager] removeItemAtPath:myCachePath error:nil]; }Copy the code
Model to dictionary
static NSSet *classes; - (NSMutableDictionary *)getParameterDictionary { NSMutableDictionary *dict = [NSMutableDictionary dictionary]; Class c = self.class; while (c) { unsigned count; objc_property_t *properties = class_copyPropertyList([c class], &count); for (int i = 0; i < count; i++) { NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])]; dict[key] = [self valueForKey:key]; } free(properties); // Get the parent class c = class_getSuperclass(c); if ([self isClassFromFoundation:c]) break; } return dict; } - (BOOL)isClassFromFoundation:(Class)c { if (c == [NSObject class] || c == [NSManagedObject class]) return YES; __block BOOL result = NO; [[self foundationClasses] enumerateObjectsUsingBlock:^(Class foundationClass, BOOL *stop) { if ([c isSubclassOfClass:foundationClass]) { result = YES; *stop = YES; } }]; return result; } - (NSSet *)foundationClasses {if (classes == nil) {// There is no NSObject in the set, because almost all classes inherit from NSObject, Classes = [NSSet setWithObjects: [NSURL class], [NSDate class], [NSValue class], [NSData class], [NSError class], [NSArray class], [NSDictionary class], [NSString class], [NSAttributedString class], nil]; } return classes; }Copy the code
45. Exchange two methods for implementation
Class aClass = [self class];
SEL originalSelector = @selector(viewWillAppear:);
SEL swizzledSelector = @selector(xxx_viewWillAppear:);
Method originalMethod = class_getInstanceMethod(aClass, originalSelector);
Method swizzledMethod = class_getInstanceMethod(aClass, swizzledSelector);
BOOL didAddMethod =
class_addMethod(aClass,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(aClass,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
Copy the code
46. Print percent signs and quotation marks
NSLog(@"%%");
NSLog(@"\"");
Copy the code
A few common permission judgment
If ([CLLocationManager authorizationStatus] = = kCLAuthorizationStatusDenied) {NSLog (@ positioning "no permission"); } AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]; If (statusVideo = = AVAuthorizationStatusDenied) {NSLog (@ "no camera authority"); } / / is there a microphone permissions AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType: AVMediaTypeAudio]; If (statusAudio = = AVAuthorizationStatusDenied) {NSLog (@ "no recording authority"); } [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) { if (status == PHAuthorizationStatusDenied) { NSLog(@" no permission ");}}];Copy the code
48. Obtain the phone model
+ (NSString *)getDeviceInfo { struct utsname systemInfo; uname(&systemInfo); NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding]; If ([platform isEqualToString:@"iPhone1,1"]) return @" iphone2g "; If ([platform isEqualToString:@"iPhone1,2"]) return @" iphone3g "; If ([platform isEqualToString:@"iPhone2,1"]) return @" iphone3gs "; If ([platform isEqualToString:@"iPhone3,1"]) return @" iphone4 "; If ([platform isEqualToString:@"iPhone3,2"]) return @" iphone4 "; If ([platform isEqualToString:@"iPhone3,3"]) return @" iphone4 "; If ([platform isEqualToString:@"iPhone4,1"]) return @" iphone4s "; If ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone5 "; If ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone5 "; If ([platform isEqualToString:@"iPhone5,3"]) return @" iphone5c "; If ([platform isEqualToString:@"iPhone5,4"]) return @" iphone5c "; If ([platform isEqualToString:@"iPhone6,1"]) return @" iphone5s "; If ([platform isEqualToString:@"iPhone6,2"]) return @" iphone5s "; If ([platform isEqualToString:@"iPhone7,1"]) return @" iphone6 Plus"; If ([platform isEqualToString:@"iPhone7,2"]) return @" iphone6 "; If ([platform isEqualToString:@"iPhone8,1"]) return @" iphone6s "; If ([platform isEqualToString:@"iPhone8,2"]) return @" iphone6s Plus"; If ([platform isEqualToString:@"iPhone9,1"]) return @" iphone7 "; if ([platform isEqualToString:@"iPhone9,1"]) return @" iphone7 "; If ([platform isEqualToString:@"iPhone9,2"]) return @" iphone7 Plus"; If ([platform isEqualToString:@"iPhone9,3"]) return @" iphone7 "; If ([platform isEqualToString:@"iPhone9,4"]) return @" iphone7 Plus"; if ([platform isEqualToString:@"iPhone9,4"]) return @" iphone7 Plus"; If ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE"; If ([platform isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G"; If ([platform isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G"; If ([platform isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G"; If ([platform isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G"; If ([platform isEqualToString:@"iPod5,1"]) return @"iPod Touch 5G"; If ([platform isEqualToString:@"iPad1,1"]) return @"iPad 1G"; If ([platform isEqualToString:@"iPad2,1"]) return @"iPad2 "; If ([platform isEqualToString:@"iPad2,2"]) return @"iPad2 "; If ([platform isEqualToString:@"iPad2,3"]) return @"iPad2 "; If ([platform isEqualToString:@"iPad2,4"]) return @"iPad2 "; If ([platform isEqualToString:@"iPad2,5"]) return @"iPad Mini 1G"; If ([platform isEqualToString:@"iPad2,6"]) return @"iPad Mini 1G"; If ([platform isEqualToString:@"iPad2,7"]) return @"iPad Mini 1G"; If ([platform isEqualToString:@"iPad3,1"]) return @"iPad3 "; If ([platform isEqualToString:@"iPad3,2"]) return @"iPad3 "; If ([platform isEqualToString:@"iPad3,3"]) return @"iPad3 "; If ([platform isEqualToString:@"iPad3,4"]) return @" ipad4 "; If ([platform isEqualToString:@"iPad3,5"]) return @" ipad4 "; If ([platform isEqualToString:@"iPad3,6"]) return @" ipad4 "; If ([platform isEqualToString:@"iPad4,1"]) return @"iPad Air"; If ([platform isEqualToString:@"iPad4,2"]) return @"iPad Air"; If ([platform isEqualToString:@"iPad4,3"]) return @"iPad Air"; If ([platform isEqualToString:@"iPad4,4"]) return @"iPad Mini 2G"; If ([platform isEqualToString:@"iPad4,5"]) return @"iPad Mini 2G"; If ([platform isEqualToString:@"iPad4,6"]) return @"iPad Mini 2G"; if ([platform isEqualToString:@"i386"]) return @"iPhone Simulator"; if ([platform isEqualToString:@"x86_64"]) return @"iPhone Simulator"; return platform; }Copy the code
Long press copy function
- (void)viewDidLoad { [self.view addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pasteBoard:)]]; } - (void)pasteBoard:(UILongPressGestureRecognizer *)longPress { if (longPress.state == UIGestureRecognizerStateBegan) { UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; Pasteboard. string = @" text to copy "; }}Copy the code
50. Cocoapods upgrade
Run sudo gem install -n /usr/local/bin cocoapods –pre on the terminal
51. After setting the startup page, the previous one is still displayed
Delete the app, reboot the phone, and reinstall it
Judge the type of picture
- (NSString *)contentTypeForImageData:(NSData *) Data {uint8_t c; [data getBytes:&c length:1]; switch (c) { case 0xFF: return @"jpeg"; case 0x89: return @"png"; case 0x47: return @"gif"; case 0x49: case 0x4D: return @"tiff"; case 0x52: if ([data length] < 12) { return nil; } NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding]; if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) { return @"webp"; } return nil; } return nil; }Copy the code
53. Get phone and app information
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary]; CFShow(infoDictionary); // app name NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"]; / / app versions nsstrings * app_Version = [infoDictionary objectForKey: @ "CFBundleShortVersionString"]. // app build version NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"]; NSString* identifierNumber = [[UIDevice currentDevice] uniqueIdentifier]; NSLog(@" phone serial number: %@",identifierNumber); // Phone alias: user-defined name NSString* userPhoneName = [[UIDevice currentDevice] name]; NSLog(@" phone alias: %@", userPhoneName); // deviceName NSString* deviceName = [[UIDevice currentDevice] systemName]; NSLog(@" deviceName: %@",deviceName); // Mobile OS version NSString* phoneVersion = [[UIDevice currentDevice] systemVersion]; NSLog(@" Mobile OS version: %@", phoneVersion); NSString* phoneModel = [[UIDevice currentDevice] model]; NSLog(@" phoneModel: %@",phoneModel); NSString* localPhoneModel = [[UIDevice currentDevice] localizedModel]; NSLog(@" Internationalized locale name: %@",localPhoneModel); NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary]; NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"]; NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"]; NSLog(@" Current app name: %@",appCurName); / / the current application software version Such as: 1.0.1 nsstrings * appCurVersion = [infoDictionary objectForKey: @ "CFBundleShortVersionString"]. NSLog(@" Current application version :%@",appCurVersion); Int NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"]; // Current application version number int NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"]; NSLog(@" Current app version number: %@",appCurVersionNum);Copy the code
Get all attributes of a class
id LenderClass = objc_getClass("Lender");
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(LenderClass, &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property));
}
Copy the code
55, image rounded corners
- (UIImage *) circleImage {/ / NO representative transparent UIGraphicsBeginImageContextWithOptions (self. The size, NO, 1); / / get the context CGContextRef CTX = UIGraphicsGetCurrentContext (); // Add a circle CGRect rect = CGRectMake(0, 0, self.size. Width, self.size. Height); / / square become circular CGContextAddEllipseInRect (CTX, the rect); / / cutting CGContextClip (CTX); // draw the image [self drawInRect:rect]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }Copy the code
56. Image stretching
+ (UIImage *)resizableImage:(NSString *)imageName { UIImage *image = [UIImage imageNamed:imageName]; CGFloat imageW = image.size.width; CGFloat imageH = image.size.height; Return [image resizableImageWithCapInsets: UIEdgeInsetsMake (, imageW imageH * 0.5 * 0.5, imageH * 0.5, ImageW * 0.5) resizingMode: UIImageResizingModeStretch]; }Copy the code
JSON string to dictionary
+ (NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
return responseJSON;
}
Copy the code
Identification number verification
- (BOOL)validateIdentityCard {
BOOL flag;
if (self.length <= 0) {
flag = NO;
return flag;
}
NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
return [identityCardPredicate evaluateWithObject:self];
}
Copy the code
59. Obtain the MAC address of the device
+ (NSString *)macAddress { int mib[6]; size_t len; char *buf; unsigned char *ptr; struct if_msghdr *ifm; struct sockaddr_dl *sdl; mib[0] = CTL_NET; mib[1] = AF_ROUTE; mib[2] = 0; mib[3] = AF_LINK; mib[4] = NET_RT_IFLIST; if((mib[5] = if_nametoindex("en0")) == 0) { printf("Error: if_nametoindex error\n"); return NULL; } if(sysctl(mib, 6, NULL, &len, NULL, 0) < 0) { printf("Error: sysctl, take 1\n"); return NULL; } if((buf = malloc(len)) == NULL) { printf("Could not allocate memory. Rrror! \n"); return NULL; } if(sysctl(mib, 6, buf, &len, NULL, 0) < 0) { printf("Error: sysctl, take 2"); return NULL; } ifm = (struct if_msghdr *)buf; sdl = (struct sockaddr_dl *)(ifm + 1); ptr = (unsigned char *)LLADDR(sdl); NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)]; free(buf); return outstring; }Copy the code
60. Import the custom font library
2. Add a line of array “Fonts provided by Application” to the plist of the project. Add an item to this key and its value is the TTF file name that you imported. Font = [UIFont fontWithName:@” TTF file name “size:20.0];
Get the controller that is currently displayed, whether it is pushed or presented
- (UIViewController *)getVisibleViewControllerFrom:(UIViewController*)vc { if ([vc isKindOfClass:[UINavigationController class]]) { return [self getVisibleViewControllerFrom:[((UINavigationController*) vc) visibleViewController]]; }else if ([vc isKindOfClass:[UITabBarController class]]){ return [self getVisibleViewControllerFrom:[((UITabBarController*) vc) selectedViewController]]; } else { if (vc.presentedViewController) { return [self getVisibleViewControllerFrom:vc.presentedViewController]; } else { return vc; }}}Copy the code
Runtime adds attributes to a class dynamically
// The essence of dynamically adding attributes is: Objc_setAssociatedObject (self, WZBPlaceholderViewKey, tagView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);Copy the code
Get attributes that Runtime dynamically added to a class
objc_getAssociatedObject(self, WZBPlaceholderViewKey);
Copy the code
64. KVO listens for properties of an object
/ / add listeners [self addObserver: self forKeyPath: property options: NSKeyValueObservingOptionNew context: nil]; - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary) *)change context:(void *)context { if ([keyPath isEqualToString:@"property"]) { [self textViewTextChange]; } else { } }Copy the code
65. Reachability Checks network status
NetworkStatus status = [[Reachability reachabilityForInternetConnection] currentReachabilityStatus]; If (status == NotReachable) {NSLog(@" Current device has no network "); } if (status == ReachableViaWiFi) {NSLog(@" current wifi network "); } if (status == ReachableViaWWAN) {NSLog(@" current cellular mobile network "); }Copy the code
AFNetworking Monitors network status
/ / to monitor network status AFNetworkReachabilityManager * MGR = [AFNetworkReachabilityManager sharedManager]; [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { switch (status) { case AFNetworkReachabilityStatusUnknown: break; case AFNetworkReachabilityStatusNotReachable: {[SVProgressHUD showInfoWithStatus: @ "current equipment without network"];} break; case AFNetworkReachabilityStatusReachableViaWiFi: [SVProgressHUD showInfoWithStatus: @ "today's wi-fi network"]; break; case AFNetworkReachabilityStatusReachableViaWWAN: [SVProgressHUD showInfoWithStatus:@" current cellular network "]; break; default: break;}}]; [mgr startMonitoring];Copy the code
Transparent colors do not affect the transparency of subviews
[UIColor colorWithRed:<#(CGFloat)#> green:<#(CGFloat)#> blue:<#(CGFloat)#> alpha:<#(CGFloat)#>];
Copy the code
68, Pick a color at a point in the picture
if (point.x < 0 || point.y < 0) return nil; CGImageRef imageRef = self.CGImage; NSUInteger width = CGImageGetWidth(imageRef); NSUInteger height = CGImageGetHeight(imageRef); if (point.x >= width || point.y >= height) return nil; unsigned char *rawData = malloc(height * width * 4); if (! rawData) return nil; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); NSUInteger bytesPerPixel = 4; NSUInteger bytesPerRow = bytesPerPixel * width; NSUInteger bitsPerComponent = 8; CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); if (! context) { free(rawData); return nil; } CGColorSpaceRelease(colorSpace); CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef); CGContextRelease(context); int byteIndex = (bytesPerRow * point.y) + point.x * bytesPerPixel; CGFloat red = (rawData[byteIndex] * 1.0) / 255.0; CGFloat green = (rawData[byteIndex + 1] * 1.0) / 255.0; CGFloat blue = (rawData[byteIndex + 2] * 1.0) / 255.0; CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0; UIColor *result = nil; result = [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; free(rawData); return result;Copy the code
69. Determine whether the image has a transparency channel
- (BOOL)hasAlphaChannel
{
CGImageAlphaInfo alpha = CGImageGetAlphaInfo(self.CGImage);
return (alpha == kCGImageAlphaFirst ||
alpha == kCGImageAlphaLast ||
alpha == kCGImageAlphaPremultipliedFirst ||
alpha == kCGImageAlphaPremultipliedLast);
}
Copy the code
70. Obtain grayscale images
+ (UIImage*)covertToGrayImageFromImage:(UIImage*)sourceImage { int width = sourceImage.size.width; int height = sourceImage.size.height; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray(); CGContextRef context = CGBitmapContextCreate (nil, width, height, 8, 0, the colorSpace, kCGImageAlphaNone); CGColorSpaceRelease(colorSpace); if (context == NULL) { return nil; } CGContextDrawImage(context,CGRectMake(0, 0, width, height), sourceImage.CGImage); CGImageRef contextRef = CGBitmapContextCreateImage(context); UIImage *grayImage = [UIImage imageWithCGImage:contextRef]; CGContextRelease(context); CGImageRelease(contextRef); return grayImage; }Copy the code
71. Read the image from the file name in the bundle
+ (UIImage *)imageWithFileName:(NSString *)name { NSString *extension = @"png"; NSArray *components = [name componentsSeparatedByString:@"."]; if ([components count] >= 2) { NSUInteger lastIndex = components.count - 1; extension = [components objectAtIndex:lastIndex]; name = [name substringToIndex:(name.length-(extension.length+1))]; } // If the screen is Retina and the corresponding image exists, return the Retina image, If ([UIScreen mainScreen].scale == 2.0) {name = [name stringByAppendingString:@"@2x"]; NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:extension]; if (path ! = nil) { return [UIImage imageWithContentsOfFile:path]; }} if ([UIScreen mainScreen].scale == 3.0) {name = [name stringByAppendingString:@"@3x"]; NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:extension]; if (path ! = nil) { return [UIImage imageWithContentsOfFile:path]; } } NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:extension]; if (path) { return [UIImage imageWithContentsOfFile:path]; } return nil; }Copy the code
72. Merge two images
+ (UIImage*)mergeImage:(UIImage*)firstImage withImage:(UIImage*)secondImage {
CGImageRef firstImageRef = firstImage.CGImage;
CGFloat firstWidth = CGImageGetWidth(firstImageRef);
CGFloat firstHeight = CGImageGetHeight(firstImageRef);
CGImageRef secondImageRef = secondImage.CGImage;
CGFloat secondWidth = CGImageGetWidth(secondImageRef);
CGFloat secondHeight = CGImageGetHeight(secondImageRef);
CGSize mergedSize = CGSizeMake(MAX(firstWidth, secondWidth), MAX(firstHeight, secondHeight));
UIGraphicsBeginImageContext(mergedSize);
[firstImage drawInRect:CGRectMake(0, 0, firstWidth, firstHeight)];
[secondImage drawInRect:CGRectMake(0, 0, secondWidth, secondHeight)];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
Copy the code
Create an ImageView based on the name of the image in the bundle
+ (id)imageViewWithImageNamed:(NSString*)imageName
{
return [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
}
Copy the code
Add a reflection to imageView
CGRect frame = self.frame; frame.origin.y += (frame.size.height + 1); UIImageView *reflectionImageView = [[UIImageView alloc] initWithFrame:frame]; self.clipsToBounds = TRUE; reflectionImageView.contentMode = self.contentMode; [reflectionImageView setImage:self.image]; ReflectionImageView. Transform = CGAffineTransformMakeScale (1.0, 1.0); CALayer *reflectionLayer = [reflectionImageView layer]; CAGradientLayer *gradientLayer = [CAGradientLayer layer]; gradientLayer.bounds = reflectionLayer.bounds; GradientLayer. Position = CGPointMake (reflectionLayer. Bounds. The size, width / 2, reflectionLayer. Bounds. Size, height * 0.5); gradientLayer.colors = [NSArray arrayWithObjects: (id)[[UIColor clearColor] CGColor], (id)[[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.3] CGColor], nil]; GradientLayer. The startPoint = CGPointMake (0.5, 0.5); GradientLayer. The endPoint = CGPointMake (0.5, 1.0); reflectionLayer.mask = gradientLayer; [self.superview addSubview:reflectionImageView];Copy the code
Paint watermark
SetImage :(UIImage *)image withWaterMark:(UIImage *)mark inRect:(CGRect)rect {if ([[[UIDevice) CurrentDevice] floatValue systemVersion]] > = 4.0) {UIGraphicsBeginImageContextWithOptions (self. Frame. The size, NO, 0.0); } // Image drawInRect:self. Bounds]; [mark drawInRect:rect]; UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); self.image = newPic; }Copy the code
Make the text content of the label appear on the top left/top right/bottom left/bottom right/top center/bottom center
TextRectForBounds :(CGRect)bounds :(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines { CGRect rect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines]; switch (self.textAlignmentType) { case WZBTextAlignmentTypeLeftTop: { rect.origin = bounds.origin; } break; case WZBTextAlignmentTypeRightTop: { rect.origin = CGPointMake(CGRectGetMaxX(bounds) - rect.size.width, bounds.origin.y); } break; case WZBTextAlignmentTypeLeftBottom: { rect.origin = CGPointMake(bounds.origin.x, CGRectGetMaxY(bounds) - rect.size.height); } break; case WZBTextAlignmentTypeRightBottom: { rect.origin = CGPointMake(CGRectGetMaxX(bounds) - rect.size.width, CGRectGetMaxY(bounds) - rect.size.height); } break; case WZBTextAlignmentTypeTopCenter: { rect.origin = CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(rect)) / 2, CGRectGetMaxY(bounds) - rect.origin.y); } break; case WZBTextAlignmentTypeBottomCenter: { rect.origin = CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(rect)) / 2, CGRectGetMaxY(bounds) - CGRectGetMaxY(bounds) - rect.size.height); } break; case WZBTextAlignmentTypeLeft: { rect.origin = CGPointMake(0, rect.origin.y); } break; case WZBTextAlignmentTypeRight: { rect.origin = CGPointMake(rect.origin.x, 0); } break; case WZBTextAlignmentTypeCenter: { rect.origin = CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(rect)) / 2, (CGRectGetHeight(bounds) - CGRectGetHeight(rect)) / 2); } break; default: break; } return rect; } - (void)drawTextInRect:(CGRect)rect { CGRect textRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines]; [super drawTextInRect:textRect]; }Copy the code
77, scrollView input box, keyboard blocking problem
Recommend using IQKeyboardManager framework! NSDictionary* info = [aNotification userInfo]; CGRect keyPadFrame=[[UIApplication sharedApplication].keyWindow convertRect:[[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue] fromView:self.view]; CGSize kbSize =keyPadFrame.size; CGRect activeRect=[self.view convertRect:activeField.frame fromView:activeField.superview]; CGRect aRect = self.view.bounds; aRect.size.height -= (kbSize.height); CGPoint origin = activeRect.origin; origin.y -= backScrollView.contentOffset.y; if (! CGRectContainsPoint(aRect, Origin)) {CGPoint scrollPoint = CGPointMake(0.0,CGRectGetMaxY(activeRect)-(arect.sie.height)); [backScrollView setContentOffset:scrollPoint animated:YES]; }Copy the code
78. Dynamic height of the frame layout cell
This usually adds an auxiliary property cellHeight to your model, overrides the get method for that property in the model, and calculates the total height based on your layout and other property values in the model. Finally, in the tableView: heightForRow method, find the corresponding model according to indexPath, and return this height.
79, AutoLayout layout cell dynamic height
/ / 1 and set properties of the tableView self. TableView. RowHeight = UITableViewAutomaticDimension; The self. The tableView. EstimatedRowHeight = 44.0; // This attribute is non-zero. Estimate the cell heightCopy the code
// 2. Set the constraint of the cell from top to bottom. Note that the top, bottom, left and right should be all around the cellCopy the code
80, Using performSelector: call function, memory leak problem
When we use in development [obj performSelector: NSSelectorFromString (@ “aMethod”)]; This type of method may receive a warning “performSelector may cause a leak because its selector is unknown”. Because the compiler doesn’t know if the object corresponds to the method, and if it doesn’t, it’s unsafe, and the compiler doesn’t know what to do with the return value of the method!
Call it with the following code: if (! obj) { return; } SEL selector = NSSelectorFromString(@"aMethod"); IMP imp = [obj methodForSelector:selector]; void (*func)(id, SEL) = (void *)imp; func(obj, selector); Or SEL selector = NSSelectorFromString(@"aMethod"); ((void (*)(id, SEL))[obj methodForSelector:selector])(obj, selector);Copy the code
81. Whether a string contains another string
If ([str1 containsString:str2]) {NSLog(@"str1 contains str2"); } else {NSLog(@"str1 does not include str2"); If ([str1 rangeOfString: str2]. Location == NSNotFound) {NSLog(@"str1 does not include str2"); } else {NSLog(@"str1 contains str2"); }Copy the code
82. Remove the selected effect of cell
cell.selectionStyle = UITableViewCellSelectionStyleNone;
Copy the code
83, Cell click effect
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
Copy the code
From 84, when deleting a xib pulled properties, must remember the xib also delete the corresponding line, or you will quote similar [0 < ViewController x7fea6ed05980 > setValue: forUndefinedKey:] : This class is not key value coding-compliant for the key crash
Could not launch “your App”, process launch failed: Security
Because your app is not online, iOS9 starts, need to manually trust Xcode generated description file, open the phone Settings -> general -> description file -> click your app description file -> trust
86, Error: Could not find Developer Disk Image
This is because the OS version of your device is larger than the OS version that Xcode is compatible with. For example, if your device is iOS10.3 and Xcode is 8.2 (Xcode8.2 is most compatible with iOS10.2), this error will be reported. The solution is to upgrade Xcode!
UITextView not placeholder problem?
There are many such custom controls on the web. You can also refer to the UITextView category I wrote uitextView-wzb
88. Remove whitespace and newlines from strings
+ (NSString *)removeSpaceAndNewline:(NSString *)str {
NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
return temp;
}
Copy the code
89, Check whether the string contains Spaces
+ (BOOL)isBlank:(NSString *)str { NSRange _range = [str rangeOfString:@" "]; if (_range.location ! NSNotFound) {// return YES; } else {// NO space return NO; }}Copy the code
Get the first frame of a video
NSURL *url = [NSURL URLWithString:filepath];
AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];
generate1.appliesPreferredTrackTransform = YES;
NSError *err = NULL;
CMTime time = CMTimeMake(1, 2);
CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];
UIImage *one = [[UIImage alloc] initWithCGImage:oneRef];
return one;
Copy the code
91. Get the duration of the video
+ (NSInteger)getVideoTimeByUrlString:(NSString *)urlString {
NSURL *videoUrl = [NSURL URLWithString:urlString];
AVURLAsset *avUrl = [AVURLAsset assetWithURL:videoUrl];
CMTime time = [avUrl duration];
int seconds = ceil(time.value/time.timescale);
return seconds;
}
Copy the code
92. Whether the string is empty
+ (BOOL)isEqualToNil:(NSString *)str { return str.length <= 0 || [str isEqualToString:@""] || ! str; }Copy the code
93. This is a common problem when uploading an app to the App Store
A lot of people say this is apple dad server problem, repeat a few times, always successful! However, after trying to find that the upload success rate is very high if you use Application Loader, so it is still recommended to export the IPA file and upload it directly using Application Loader. If the Application Loader fails, you need to check your network. Sometimes VPN can improve the speed.
94, When the tableView occupies less than a screen, remove the extra cells below
self.tableView.tableHeaderView = [UIView new];
self.tableView.tableFooterView = [UIView new];
Copy the code
95, isKindOfClass and isMemberOfClass difference
IsKindOfClass determines whether an object belongs to a class or a subclass of that class. IsMemberOfClass is more precise, it can only determine if the object type is the class (not the subclass)Copy the code
96, __block
When a local variable to change in the block, the need to define plus __block when decorate, specific look at the official documentation developer.apple.com/library/ios…
97, -[ViewController aMethod:]: Unrecognized selector sent to instance 0x7fe91e607fB0
This is a classic error. The ViewController cannot respond to the aMethod method. The reason may be that the aMethod method is not implemented in the ViewController file
98, UITableView (<UITableView: 0x7ff19b027000; >) failed to obtain a cell from its dataSource (<ViewController: 0x7ff19a507520>)
This is the reason for the error tableView proxy method – tableView: cellForRowAtIndexPath: need to return a UITableViewCell, and you return a nil. The other thing is that this place that doesn’t return a value of type UITableViewCell will crash as well
Constraint how to animate UIView?
2. Add code where you need to animate the constant property of this property. 3. @property (weak, nonatomic) IBOutlet NSLayoutConstraint *buttonTopConstraint; self.buttonTopConstraint.constant = 100; [UIView animateWithDuration:.5 animations:^{ [self.view layoutIfNeeded]; }];Copy the code
Get the link string from NSURL
NSString *urlString = myURL.absoluteString;
Copy the code
Scroll the tableView to the top
[tableView setContentOffset:CGPointZero animated:YES]; Or [tableView scrollRectToVisible: CGRectMake (0, 0, 1, 1) animated: YES];Copy the code
102, if use addTarget: action: forControlEvents: methods to click a button to add a lot of events, at some point to a deleted? All you need to do is call the following line
[youButton removeTarget:nil action:nil forControlEvents:UIControlEventAllEvents];
Copy the code
103, The height of a font
font.lineHeight;
Copy the code
Delete all subviews of a view
[[someView subviews]
makeObjectsPerformSelector:@selector(removeFromSuperview)];
Copy the code
105, Delete all NSUserDefaults records
// NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier]; [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain]; Void setDefaults {NSUserDefaults * defs = [NSUserDefaults * defs]; NSDictionary * dict = [defs dictionaryRepresentation]; for (id key in dict) { [defs removeObjectForKey:key]; } [defs synchronize]; [NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[NSBundle mainBundle] bundleIdentifier]];Copy the code
106. Disable the system slide back function
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {self.navigationController.interactivePopGestureRecognizer.delegate = self;
}
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {self.navigationController.interactivePopGestureRecognizer.delegate = nil;
}
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
return NO;
}
Copy the code
107. The simulator reported an error
Open the Simulator-> Simulator->Reset Content and Settings… If not, reboot!
108. Customize cell Select the background color
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];
Copy the code
109. UILabel sets the inner margin
UIEdgeInsets = {0, 5, 0, 5}; void drawTextInRect (void drawTextInRect) {UIEdgeInsets = {0, 5, 0, 5}; [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)]; }Copy the code
UILabel sets text stroke
Subclass UILabel, rewrite drawTextInRect method - (void) drawTextInRect: (CGRect) the rect {CGContextRef c = UIGraphicsGetCurrentContext (); CGContextSetLineWidth(c, 1); CGContextSetLineJoin(c, kCGLineJoinRound); CGContextSetTextDrawingMode(c, kCGTextStroke); Self. textColor = [UIColor redColor]; [super drawTextInRect:rect]; Self. textColor = [UIColor yellowColor]; CGContextSetTextDrawingMode(c, kCGTextFill); [super drawTextInRect:rect]; }Copy the code
111. Screenshot using simulator
Shortcut command + S or File->Save Screen Shot
112, scrollView scroll to the bottom
CGPoint bottomOffset = CGPointMake(0, scrollView.contentSize.height - scrollView.bounds.size.height);
[scrollView setContentOffset:bottomOffset animated:YES];
Copy the code
UIView background color gradient
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
[self.view addSubview:view];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[view.layer insertSublayer:gradient atIndex:0];
Copy the code
114, Stop UIView animation
[yourView.layer removeAllAnimations]
Copy the code
115. Add a rounded corner to a corner of UIView
/ / the top left corner and the bottom right hand corner to add rounded corners UIBezierPath * maskPath = [UIBezierPath bezierPathWithRoundedRect: the bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerBottomRight) cornerRadii:CGSizeMake(20, 20)]; CAShapeLayer *maskLayer = [CAShapeLayer layer]; maskLayer.frame = view.bounds; maskLayer.path = maskPath.CGPath; view.layer.mask = maskLayer;Copy the code
116, Delete Xcode Derived Data cache data
Click Xcode -> Preferences -> Location, and then click the Derived Data path to go to the little arrow and delete the data under that folder, as shown
Place a view at the top of its sibling view
[parentView bringSubviewToFront:yourView]
Copy the code
Place a view at the bottom of its sibling view
[parentView sendSubviewToBack:yourView]
Copy the code
Let the phone vibrate
Add in frame # import < AudioToolbox/AudioToolbox. H > AudioServicesPlayAlertSound (kSystemSoundID_Vibrate); Or AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);Copy the code
120, When is the layoutSubviews method called?
The addSubview method is called when the bounds change The layoutSubviews method of scrollView will be called when the scrollView is rolled (so it is not recommended to do complex logic in the layoutSubviews method of scrollView) Blog.logichigh.com/2011/03/16/…
121, Line wrap UILabel in the specified place
// The newline character is \n, which can be added to places where newlines are needed, for example, label.numberoflines = 0; Label. text = @" here \n newline ";Copy the code
122. Shake the function
1, open the shake function [UIApplication sharedApplication]. ApplicationSupportsShakeToEdit = YES; 2, let the controller that needs to be shaken become the first responder [self becomeFirstResponder]; // start shaking - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event // end of motion - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)eventCopy the code
123. Get the image size
CGFloat imageWidth = image.size.width;
CGFloat imageHeight = imageWidth * image.scale;
Copy the code
Get the view coordinate position on the entire window
CGPoint point = [v convertPoint:CGPointMake(0, 0) 0) toView:[UIApplication sharedApplication].windows.lastObject]; Or CGPoint point = [v. uperview convertPoint: v. rame. Origin toView: [UIApplication sharedApplication].windows.lastObject];Copy the code
125. Restrictions on submission to App Store review procedures
The uncompressed size of your application must be less than 4GB. Each Mach-O executable (e.g. App_name.app /app_name) cannot exceed these limits: for applications where MinimumOSVersion is less than 7.0: __TEXT The total number of all parts in the binary is at most 80 MB.
For Minimumosversion7.x to 8.x applications: __TEXT Maximum 60 MB for each fragment of each architectural fragment in the binary. For MinimumOSVersion9.0 or later applications: the total number of all parts in the __TEXT binary is at most 500 MB. See also: iTunes Connect Developer’s Guide
126, Change the font size of UISegmentedControl
[segment setTitleTextAttributes: @ {NSFontAttributeName: [UIFont systemFontOfSize: 15.0 f]} forState: UIControlStateNormal];Copy the code
The UIAlertController dialog box is displayed where the ViewController is not
/ / the best smoke into a classification UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @ "Title" message: @ "message" preferredStyle:UIAlertControllerStyleAlert]; / /... id rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController; if([rootViewController isKindOfClass:[UINavigationController class]]) { rootViewController = ((UINavigationController *)rootViewController).viewControllers.firstObject; } if([rootViewController isKindOfClass:[UITabBarController class]]) { rootViewController = ((UITabBarController *)rootViewController).selectedViewController; } [rootViewController presentViewController:alertController animated:YES completion:nil];Copy the code
Get a view controller
BelongViewController {for (UIView *next = [self superview]; next; next = next.superview) { UIResponder* nextResponder = [next nextResponder]; if ([nextResponder isKindOfClass:[UIViewController class]]) { return (UIViewController *)nextResponder; } } return nil; }Copy the code
UIImage and base64 interswitch
- (NSString *)encodeToBase64String:(UIImage *)image {return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]; } - (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData { NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters]; return [UIImage imageWithData:data]; }Copy the code
UIWebView set background transparency
[webView setBackgroundColor:[UIColor clearColor]];
[webView setOpaque:NO];
Copy the code
NSDate is today
NSDateComponents *otherDay = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate]; NSDateComponents *today = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]]; if([today day] == [otherDay day] && [today month] == [otherDay month] && [today year] == [otherDay year] && [today era] == [otherDay era]) {// is today}Copy the code
132, Set the color of tableView divider
[self.tableView setSeparatorColor:[UIColor myColor]];
Copy the code
133. Set screen orientation
NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
[UIViewController attemptRotationToDeviceOrientation];
Copy the code
Compare the two colors for equality
- (BOOL)isEqualToColor:(UIColor *)otherColor {
CGColorSpaceRef colorSpaceRGB = CGColorSpaceCreateDeviceRGB();
UIColor *(^convertColorToRGBSpace)(UIColor*) = ^(UIColor *color) {
if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) == kCGColorSpaceModelMonochrome) {
const CGFloat *oldComponents = CGColorGetComponents(color.CGColor);
CGFloat components[4] = {oldComponents[0], oldComponents[0], oldComponents[0], oldComponents[1]};
CGColorRef colorRef = CGColorCreate( colorSpaceRGB, components );
UIColor *color = [UIColor colorWithCGColor:colorRef];
CGColorRelease(colorRef);
return color;
} else
return color;
};
UIColor *selfColor = convertColorToRGBSpace(self);
otherColor = convertColorToRGBSpace(otherColor);
CGColorSpaceRelease(colorSpaceRGB);
return [selfColor isEqual:otherColor];
}
Copy the code
135, tableViewCell splitter line top to end
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
[cell setSeparatorInset:UIEdgeInsetsZero];
[cell setLayoutMargins:UIEdgeInsetsZero];
cell.preservesSuperviewLayoutMargins = NO;
}
- (void)viewDidLayoutSubviews {
[self.tableView setSeparatorInset:UIEdgeInsetsZero];
[self.tableView setLayoutMargins:UIEdgeInsetsZero];
}
Copy the code
Don’t let the controller’s view stretch or compress with the controller’s XIB
self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
Copy the code
CocoaPods error: [!] Unable to add a source with urlhttps://github.com/CocoaPods/Specs.git
named master-1
.
You can try adding it manually in ~/.cocoapods/repos
or via pod repo add
.
Sudo xcode-select-switch /Applications/ xcode.app is used by cocoapods because another Xcode is installed on the PC
ERROR: While Executing Gem… (Errno::EPERM)
Operation not permitted - /usr/bin/pod
Copy the code
Solution: Directly run sudo gem install -n /usr/local/bin cocoapods on the terminal
139. Add a web request chrysanthemum to the status bar, similar to how Safari loads web pages
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
Copy the code
140, Check if a recT contains a point
BOOL isContains = CGRectContainsPoint(rect, point);Copy the code
141, Let UILabel automatically set the best font for the specified width
label.adjustsFontSizeToFitWidth = YES;
Copy the code
142. Save an image in an album
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil); Or #import <Photos/ photos.h > [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{PHAssetChangeRequest *changeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image]; changeRequest.creationDate = [NSDate date]; } completionHandler:^(BOOL success, NSError *error) { if (success) { NSLog(@"successfully saved"); } else { NSLog(@"error saving to photos: %@", error); } }];Copy the code
143, Change the size of cell.imageView
UIImage *icon = [UIImage imageNamed:@""]; CGSize itemSize = CGSizeMake(30, 30); UIGraphicsBeginImageContextWithOptions (itemSize, NO, 0.0); CGRect imageRect = CGRectMake(0.0, 0.0, itemsize.width, itemsize.height); [icon drawInRect:imageRect]; cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();Copy the code
144. Add a dotted border to a view
CAShapeLayer *border = [CAShapeLayer layer]; Border-.strokecolor = [UIColor colorWithRed:67/255.0f green:37/255.0f blue:83/255.0f alpha:1].cgcolor; border.fillColor = nil; border.lineDashPattern = @[@4, @2]; border.path = [UIBezierPath bezierPathWithRect:view.bounds].CGPath; border.frame = view.bounds; [view.layer addSublayer:border];Copy the code
145, UITextView enable or disable copy, cut, select, select all functions
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender { If (action == @selector(paste:)) return NO; If (action == @selector(cut:)) return NO; If (action == @selector(copy:)) return NO; // select if (action == @selector(select:)) return NO; // selectAll if (action == @selector(selectAll:) return NO; If (action == @selector(delete:)) return NO; If (action == @selector(share)) return NO; return [super canPerformAction:action withSender:sender]; }Copy the code