iOS Development Skills (I)

Posted by spaze on Tue, 18 Jun 2019 23:21:19 +0200

1. Prohibit Cell Phone Sleep

[UIApplication sharedApplication].idleTimerDisabled = YES;

2. Hide a line of cell s

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// If you need to hide the line, return to the height of 0.
    if(indexPath.row == YouWantToHideRow)
        return 0; 
    return 44;
}

// Then call it when you need to hide the cell
[self.tableView beginUpdates];
[self.tableView endUpdates];

3. Disable button highlighting

button.adjustsImageWhenHighlighted = NO;
Or at the time of creation
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

4. tableview encountered this error failed to obtain a cell from its dataSource

Because your cell was called early. Cells are recycled and then created. The order is wrong.

Possible reasons: 1. xib's cell is not registered. 2. The cell's cache already exists in memory (that is, the cell found through your cell ID is not the type you want). At this time, the cell's identity needs to be changed.

5. cocoa pods reported this error: unable to access'https://github.com/facebook/pop.git/': Operation timed out after 0 milliseconds with 0 out of 0 bytes received

Solution: The reason may be a network problem. The network request is timed out. Just try again.

6. ERROR appears in cocoa pods: while executing gem. (Errno:: EPERM)

Solution: https://segmentfault.com/q/1010000002926243

7. Root Controller of Animation Switching Windows

// 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) {
    }];

8. Remove duplicate objects from arrays

NSArray *newArr = [oldArr valueForKeyPath:@"@distinctUnionOfObjects.self"];

9. no such file or directory:/users/apple/XXX is encountered during compilation

Because when compiling, this file can not be found under this path. To solve this problem, the first thing is to check whether the missing file is in the project, if not in the project, it needs to be dragged in locally, if it is found that the project already exists, or dragged in or reported an error, then it needs to go to build phases to search for this file, which is likely to be found out at this time. Now two identical files, at this time, one path is correct, delete the other one. If deleted or not, you need to delete both and drag the file back into the project.

10. In iOS 8 system, tableView is best implemented under - tableView: heightForRowAtIndexPath: This proxy method, otherwise in iOS 8 there may be problems of incomplete display or inability to respond to events.

11. This method must be implemented when implementing side slip function in iOS8. Otherwise, side slip can not be achieved in iOS8.

// The method you have to write is paired with editActions ForRow AtIndexPath, and you can write nothing in it.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

}

12. Three Notices

NSSystem Time Zone DidChange Notification listens for two button state changes in the modified time interface
 UI Application Significant Time Change Notification listens for the user to change the time (it will be called by clicking the Auto Settings button) 
NSSystemClockDidChangeNotification listens for user modification times (only when different times are invoked)

13. SDWebImage local caching can sometimes be harmful. If you have cached a picture before, even if the next server changes this picture, but the url of the picture is not changed, the one downloaded with sdwebimage is the same one before, so when you encounter this problem, don't go to the server first, empty the cache and try again.

14. Attention before going online:

1) Delete all test code from the code

2) If there is an audit mode in the background, remind the background to open this mode.

3) Run the mainstream again

4) Global search waring, checking where all tags are Waring

15. Jump into app permission settings

// Jump into app settings
if (UIApplicationOpenSettingsURLString != NULL) {

     NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    [[UIApplication sharedApplication] openURL:url];
}

16. Give a view screenshot

UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

17. In development, if you want to dynamically change the height of tableHeaderView or tableFooterView of tableView, you need to reset the tableView instead of directly changing the height. The correct way to do this is to reset tableView.tableFooterView = to change the view too high. Why? In fact, it is no problem to change the height directly above iOS 8. The inaccuracy of content Size appears in iOS 8, which is the solution.

18. Note that when the object is nil, the method calling the object classification will not execute

19. collectionView cannot scroll when its content is smaller than its width and height. Settings can scroll:

collectionView.alwaysBounceHorizontal = YES;
collectionView.alwaysBounceVertical = YES;

20. Set title color and size on navigationBar

[self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor youColor], NSFontAttributeName : [UIFont systemFontOfSize:15]}]

21. Color Transfer Pictures

+ (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;
}

22. view sets 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 corner

23. Strong/Weak Citation

#define WeakSelf(type)  __weak typeof(type) weak##type = type; // weak
#define StrongSelf(type)  __strong typeof(type) type = weak##type; // strong

24. Conversion of Radius from Angle

#define DegreesToRadian(x) (M_PI * (x) / 180.0)

25. Conversion of angle from radian

#define RadianToDegrees(radian) (radian*180.0)/(M_PI)

26. Access to Photo Resources

#define GetImage(imageName) [UIImage imageNamed:[NSString stringWithFormat:@"%@",imageName]]

27. Getting temp

#define PathTemp NSTemporaryDirectory()

28. Getting Sandbox Document

#define PathDocument [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]

29. Getting Sandbox Cache

#define PathCache [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]

30. GCD code is executed only once

#define kDISPATCH_ONCE_BLOCK(onceBlock) static dispatch_once_t onceToken; dispatch_once(&onceToken, onceBlock);

31. Customize NSLog

#ifdef DEBUG
#define NSLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#define NSLog(...)
#endif

32,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)

33,FORMAT

#define FORMAT(f, ...)      [NSString stringWithFormat:f, ## __VA_ARGS__]

34. Running on the main thread

#define kDISPATCH_MAIN_THREAD(mainQueueBlock) dispatch_async(dispatch_get_main_queue(), mainQueueBlock);

35. Open asynchronous threads

#define kDISPATCH_GLOBAL_QUEUE_DEFAULT(globalQueueBlock) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), globalQueueBlocl);

36. Notification

#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]

37. Random color

+ (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.0f];
    return randColor;
}

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;
}

39. Modify the placeholder font color and size of textField

[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

40. Uniform Keyboard Collection

[[[UIApplication sharedApplication] keyWindow] endEditing:YES];

41. Controlling screen rotation and writing in controller

/** Whether Automatic Screen Revolving is Supported */
- (BOOL)shouldAutorotate {
    return YES;
}

/** Which screen directions are supported */
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
}

/** The default screen orientation (the current ViewController must be displayed in a modal UIViewController (modal navigation invalid) way before this method can be invoked) */
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationLandscapeLeft | UIInterfaceOrientationLandscapeRight;
}

42. Get app cache size

- (CGFloat)getCachSize {

    NSUInteger imageCacheSize = [[SDImageCache sharedImageCache] getSize];
    //Get custom cache size
    //Traversing the contents of a folder with an enumerator
    //1. Get folder enumerator
    NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
    NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:myCachePath];
    __block NSUInteger count = 0;
    //2. Traversal
    for (NSString *fileName in enumerator) {
        NSString *path = [myCachePath stringByAppendingPathComponent:fileName];
        NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
        count += fileDict.fileSize;//Customize all cache sizes
    }
    // The result is that bytes are converted into M
    CGFloat totalSize = ((CGFloat)imageCacheSize+count)/1024/1024;
    return totalSize;
}

43. Clean up app cache

- (void)handleClearView {
    //Delete two parts
    //1. Delete sd image cache
    //Clear the image cache in memory first
    [[SDImageCache sharedImageCache] clearMemory];
    //Clear the cache of the disk
    [[SDImageCache sharedImageCache] clearDisk];
    //2. Delete your own cache
    NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
    [[NSFileManager defaultManager] removeItemAtPath:myCachePath error:nil];
}

44. 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 collection, because almost all classes are inherited from NSObject. Does NSObject need special judgment?
        classes = [NSSet setWithObjects:
                              [NSURL class],
                              [NSDate class],
                              [NSValue class],
                              [NSData class],
                              [NSError class],
                              [NSArray class],
                              [NSDictionary class],
                              [NSString class],
                              [NSAttributedString class], nil];
    }
    return classes;
}

45. Implementing Two Methods of Exchange

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); 
        }

46. Print Percentage and Quotation Marks

NSLog(@"%%");
NSLog(@"\"");

47. Judgment of Several Common Permissions

if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
    NSLog(@"No Location Permission");
}
AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (statusVideo == AVAuthorizationStatusDenied) {
    NSLog(@"No camera privileges");
}
//Do you have microphone access?
AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
if (statusAudio == AVAuthorizationStatusDenied) {
    NSLog(@"No recording rights");
}
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
    if (status == PHAuthorizationStatusDenied) {
        NSLog(@"No album permission");
    }
}];

48. Get the Model of Mobile Phone

+ (NSString *)getDeviceInfo {
struct utsname systemInfo;
uname(&systemInfo);
NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
// Both Nikko models are Japanese-owned and may use Sony FeliCa's payment scheme instead of Apple's.
if ([platform isEqualToString:@"iPhone9,1"])    return @"National Bank, Japanese Edition, Hong Kong Bank iPhone 7";
if ([platform isEqualToString:@"iPhone9,2"])    return @"Bank of Hong Kong and Bank of China iPhone 7 Plus";
if ([platform isEqualToString:@"iPhone9,3"])    return @"American edition, Taiwan Edition iPhone 7";
if ([platform isEqualToString:@"iPhone9,4"])    return @"American edition, Taiwan Edition iPhone 7 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 @"iPad 2";
if ([platform isEqualToString:@"iPad2,2"]) return @"iPad 2";
if ([platform isEqualToString:@"iPad2,3"]) return @"iPad 2";
if ([platform isEqualToString:@"iPad2,4"]) return @"iPad 2";
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 @"iPad 3";
if ([platform isEqualToString:@"iPad3,2"]) return @"iPad 3";
if ([platform isEqualToString:@"iPad3,3"]) return @"iPad 3";
if ([platform isEqualToString:@"iPad3,4"]) return @"iPad 4";
if ([platform isEqualToString:@"iPad3,5"]) return @"iPad 4";
if ([platform isEqualToString:@"iPad3,6"]) return @"iPad 4";
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;
}

49. Long Press Replication 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 be copied";
    }
}

50. cocoapods Upgrade

Perform sudo gem install-n/usr/local/bin cocoapods at the terminal -- pre

51. After setting the startup page, it still displays the previous one.

Delete app, restart phone, reinstall

52. Judging Picture Types

//Get the image extension by the first byte of the image Data
- (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;
}

53. Access to Mobile Phone and app Information

NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
CFShow(infoDictionary);
// app name
NSString *appName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
// app version
NSString *appVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
// app build version
NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];

//Mobile phone serial number
NSString* identifierNumber = [[UIDevice currentDevice] uniqueIdentifier];
NSLog(@"Mobile phone serial number: %@",identifierNumber);
//Mobile Alias: User-defined Names
NSString* userPhoneName = [[UIDevice currentDevice] name];
NSLog(@"Mobile Alias: %@", userPhoneName);
//Name of device
NSString* deviceName = [[UIDevice currentDevice] systemName];
NSLog(@"Name of device: %@",deviceName );
//Mobile System Version
NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
NSLog(@"Mobile System Version: %@", phoneVersion);
//Mobile phone model
NSString* phoneModel = [[UIDevice currentDevice] model];
NSLog(@"Mobile phone model: %@",phoneModel );
//Local model (international regional name)
NSString* localPhoneModel = [[UIDevice currentDevice] localizedModel];
NSLog(@"Name of internationalized region: %@",localPhoneModel );

NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
// Current application name
NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
NSLog(@"Current application name:%@",appCurName);
// Current versions of applications such as: 1.0.1
NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
NSLog(@"Current version of application software:%@",appCurVersion);
// Current application version number int type
NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];
NSLog(@"Current application version number:%@",appCurVersionNum);

54. 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));
}

55. image rounded corners

- (UIImage *)circleImage{
    // NO stands for transparency
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 1);
    // Get context
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    // Add a circle
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    // Square to circle
    CGContextAddEllipseInRect(ctx, rect);
    // Tailoring
    CGContextClip(ctx);
    // Draw the picture on it.
    [self drawInRect:rect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

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(imageH * 0.5, imageW * 0.5, imageH * 0.5, imageW * 0.5) resizingMode:UIImageResizingModeStretch];
}

57. JSON String Conversion Dictionary

+ (NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
    return responseJSON;
}

58. Identity Card 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];
}

59. Get 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:@"X:X:X:X:X:X",
                           *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    free(buf);

    return outstring;
}

Import custom font library

1. Find the ttf format of the font you want to use and drag it into the project

2. Add an array of rows to the plist of the project, "Fonts provided by application"

3. Add an item to the key and value is the name of the ttf file you just imported.

4. Use it directly: label. font = [UIFont font WithName:@ "The name of the ttf file you just imported" size:20.0];

61. Get the controller that is currently being displayed, whether it's push in or press in.

- (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;
        }
    }
}

62. runtime dynamically adds attributes to a class

// The essence of dynamically adding attributes is to associate an attribute of an object with a value.
        objc_setAssociatedObject(self, WZBPlaceholderViewKey, placeholderView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

63. Get properties that runtime dynamically adds to a class

objc_getAssociatedObject(self, WZBPlaceholderViewKey);

64. KVO listens for attributes of an object

// Adding listeners
[self addObserver:self forKeyPath:property options:NSKeyValueObservingOptionNew context:nil];

// This approach comes when the value of the monitored attribute changes
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"property"]) {
       [self textViewTextChange];
       } else {
     }
}

65. Reachability Judges Network State

NetworkStatus status = [[Reachability reachabilityForInternetConnection] currentReachabilityStatus];
    if (status == NotReachable) {
        NSLog(@"Current devices have no network");
    }
    if (status == ReachableViaWiFi) {
        NSLog(@"current wifi network");
    }
    if (status == NotReachable) {
        NSLog(@"Current cellular mobile networks");
    }

AF Network Monitoring Network Status

// Monitoring network status
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                break;
            case AFNetworkReachabilityStatusNotReachable: {
                [SVProgressHUD showInfoWithStatus:@"Current devices have no network"];
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [SVProgressHUD showInfoWithStatus:@"current Wi-Fi network"];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                [SVProgressHUD showInfoWithStatus:@"Current cellular mobile networks"];
                break;
            default:
                break;
        }
    }];
    [mgr startMonitoring];

67. Transparent color does not affect sub-view transparency

[UIColor colorWithRed: green: blue: alpha:];

68. Take the color of 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;

69. Judge whether the picture has a transparency channel

  - (BOOL)hasAlphaChannel
{
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(self.CGImage);
    return (alpha == kCGImageAlphaFirst ||
            alpha == kCGImageAlphaLast ||
            alpha == kCGImageAlphaPremultipliedFirst ||
            alpha == kCGImageAlphaPremultipliedLast);
}

70. Getting Gray Gray Image

+ (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,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;
}

71. Read pictures according to file names in bundle s

   + (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 there is a Retina screen and a corresponding picture, return the Retina picture, otherwise look for the ordinary picture.
    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;
}

72. Merge two pictures

+ (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;
}

73. Create an image view based on the image name in the bundle

+ (id)imageViewWithImageNamed:(NSString*)imageName
{
    return [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
}

74. Adding reflections 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.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.startPoint = CGPointMake(0.5,0.5);
gradientLayer.endPoint = CGPointMake(0.5,1.0);
reflectionLayer.mask = gradientLayer;

[self.superview addSubview:reflectionImageView];

75. Watermarking

// Drawing Watermarking
- (void) setImage:(UIImage *)image withWaterMark:(UIImage *)mark inRect:(CGRect)rect
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0)
    {
        UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0.0);
    }
    //Original graph
    [image drawInRect:self.bounds];
    //Watermarking
    [mark drawInRect:rect];
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    self.image = newPic;
}

76. Let label's text be displayed on top left/top right/bottom left/bottom right/top centre/bottom Centre

custom UILabel
// Rewriting label's textRectForBounds method
- (CGRect)textRectForBounds:(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];
}

77. Input box on scrollView, problems blocked by keyboard

IQ Keyboard Manager is recommended! Manual solutions are as follows

1. Monitor the notification of keyboard pop-up/disappearance 2. Add code to the notification:

    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.size.height));
        [backScrollView setContentOffset:scrollPoint animated:YES];
    }

78. cell Dynamic Height of frame Layout

This method usually adds an auxiliary attribute cell Height to your model, rewrites the get method of this attribute in the model, and calculates the total height based on your layout and other attribute values in the model. Finally, in the tableView: heightForRow method, the corresponding model is found according to indexPath and returned to this height.

79. cell Dynamic Height of AutoLayout Layout Layout

// 1. Setting the properties of tableView

    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 44.0; // This attribute is not zero, estimating cell height

// 2. Setting cell constraints from top to bottom. Note that it's best to top up around the cell from top to bottom.

80. Using performSelector: Calling Functions, Memory Leakage Problem

When we use [obj performance selector: NSSelector FromString (@ "a method") in development, we may receive a warning that "performance selector may cause a leak because its selector is unknown".

Because the compiler does not know whether this object can correspond to this method, if not, it is unsafe, and the compiler does not know how to deal with the return value of this method!

Call 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);

81. Does one string contain another string?

// Method 1
if ([str1 containsString:str2]) {
        NSLog(@"str1 Contain str2");
    } else {
        NSLog(@"str1 Not included str2");
    }

// Method 2
if ([str1 rangeOfString: str2].location == NSNotFound) {
        NSLog(@"str1 Contain str2");
    } else {
        NSLog(@"str1 Not included str2");
    }

82. cell Removal and Selection Effect

cell.selectionStyle = UITableViewCellSelectionStyleNone;

83. cell Point by Effect

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

84. When deleting an attribute dragged from xib, be sure to delete the corresponding line in xib, otherwise it will report a crash similar to [setValue: for Undefined Key:]: this class is not key value coding-compliant for the key

Click on this cross to delete

85. Error reporting during real-time testing: Can not launch "your App", process launch failed: Security

Since your app is not online, iOS 9 starts by manually trusting the description file generated by Xcode, opening the mobile settings - > generic - > description file - > Clicking on your app's description file - > Clicking on trust

86. Error reporting during real machine testing: Can not find Developer Disk Image

This is because your device system version is larger than the compatible system version of Xcode, such as your device is iOS 10.3, and the Xcode version is 8.2 (Xcode 8.2 is the most compatible iOS 10.2), this error will be reported. The solution is to upgrade Xcode!

87. UITextView has no placeholder problem?

There are many such custom controls on the Internet. You can also refer to a UITextView classification UITextView-WZB I wrote.

88. Remove spaces 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;
}

89. Determine whether there are spaces in a string

+ (BOOL)isBlank:(NSString *)str {
    NSRange _range = [str rangeOfString:@" "];
    if (_range.location != NSNotFound) {
        //Space
        return YES;
    } else {
        //No spaces
        return NO;
    }
}

90. 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;

91. The length of video acquisition

+ (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;
}

92. Is the string empty

+ (BOOL)isEqualToNil:(NSString *)str {
    return str.length <= 0 || [str isEqualToString:@""] || !str;
}

93. This is a common problem when uploading apps to the App Store

try again

Many people say that this is the problem of Apple Dad's server. If you try it several times, you will succeed!

But after trying to find that if you use Application Loader upload success rate is very high, so it is recommended to export the ipa file and upload directly with Application Loader.

If Application Loader doesn't work, you need to check your network, and sometimes vpn will speed up.

94. When the tableView occupies less than one screen, remove the redundant cells below

self.tableView.tableHeaderView = [UIView new];
self.tableView.tableFooterView = [UIView new];

Differences between isKindOfClass and isMemberOfClass

isKindOfClass can determine whether an object belongs to a class or a subclass of that class. isMemberOfClass is more precise, it can only judge whether the object type is this class (not subclass).

96,__block

When a local variable needs to be changed in a block, it needs to be modified with _block when defining it. See the official documentation for details. http://developer.apple.com/library/ios/documentation/cocoa/Conceptual/Blocks/Articles/bxVariables.html #//appleref/doc/uid/TP40007502-CH6-SW6

97,-[ViewController aMethod:]: unrecognized selector sent to instance 0x7fe91e607fb0

This is a classic error. ViewController cannot respond to the aMethod method. The reason for this error may be that the aMethod method is not implemented in the viewController file.

98,UITableView () failed to obtain a cell from its dataSource ()

The reason for this error is that the proxy method of tableView - tableView:cellForRowAtIndexPath: needs to return a UITableViewCell, and you return a nil. In addition, the return value of this place is not UITableViewCell type, which can also cause crashes.

99. How do constraints animate UIView?

1. Drag a line of constraints that need to be changed to be attributes

2. Add code where animation is needed to change the constant property of this property

3. Start making UIView animation. Call the layoutIfNeeded method in the animation.

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *buttonTopConstraint;
self.buttonTopConstraint.constant = 100;
    [UIView animateWithDuration:.5 animations:^{
        [self.view layoutIfNeeded];
    }];

100. Get the link string from the NSURL

NSString *urlString = myURL.absoluteString;

101. Scroll tableView to the top

[tableView setContentOffset:CGPointZero animated:YES];
//perhaps
[tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];

102. What if you add a lot of click events to a button using the addTarget: action: for ControlEvents: method, and want to delete them at a certain time? Just call the code below.

[youButton removeTarget:nil action:nil forControlEvents:UIControlEventAllEvents];

103. Height of a font

font.lineHeight;

104. Delete all subviews of a view

[[someView subviews]
 makeObjectsPerformSelector:@selector(removeFromSuperview)];

105. Delete all records of NSUserDefaults

//Method 1
  NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
 [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];   
 //Method 2  
- (void)resetDefaults {   
  NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
     NSDictionary * dict = [defs dictionaryRepresentation];
     for (id key in dict) {
          [defs removeObjectForKey:key];
     }
      [defs synchronize];
 }
// Method 3
[[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];

106. Disable the sliding return function of the system

- (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;
}

107. Simulator Error Reporting

Simulator error reporting

Solution:

Open the simulator - > Simulator - > Reset Content and Settings...

If not, try restarting!

108. Customize cell to select background color

UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];

UILabel Sets Inside Margin

Subclass UILabel, Rewrite DraTextInRect Method

- (void)drawTextInRect:(CGRect)rect {
    // Margin, top left, bottom right
    UIEdgeInsets insets = {0, 5, 0, 5};
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}

110. UILabel Sets Text Edge

Subclass UILabel, Rewrite DraTextInRect Method

- (void)drawTextInRect:(CGRect)rect{
    CGContextRef c = UIGraphicsGetCurrentContext();
    // Set the stroke width
    CGContextSetLineWidth(c, 1);
    CGContextSetLineJoin(c, kCGLineJoinRound);
    CGContextSetTextDrawingMode(c, kCGTextStroke);
    // stroke color
    self.textColor = [UIColor redColor];
    [super drawTextInRect:rect];
    // text color
    self.textColor = [UIColor yellowColor];
    CGContextSetTextDrawingMode(c, kCGTextFill);
    [super drawTextInRect:rect];
}

111. Use simulator screenshots

Keyboard shortcut command + s
 Or File - > Save Screen Shot

112. scrollView scrolls to the bottom

CGPoint bottomOffset = CGPointMake(0, scrollView.contentSize.height - scrollView.bounds.size.height);
[scrollView setContentOffset:bottomOffset animated:YES];

113. 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];

114. Stop UIView animation

[yourView.layer removeAllAnimations]

115. Adding rounded corners to a corner of UIView

// Add rounded corners to upper left and lower right corners
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerBottomRight) cornerRadii:CGSizeMake(20, 20)];
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;

116. Delete Xcode Derived data cache data

Click Xcode - > Preferences - > location in turn, then click the Derived data path and go to the small arrow to delete the data under this folder, as shown in the figure.

Xcode Derived data

117. Place a view at the top of its sibling view

[parentView bringSubviewToFront:yourView]

Place a view at the bottom of its sibling view

[parentView sendSubviewToBack:yourView]

119. Let the mobile phone shake

Pour in the framework # import Audio Services PlayAlert Sound (kSystem SoundID Vibrate); or Audio Services PlaySystem Sound (kSystem SoundID Vibrate);

120. When is the layoutSubviews method called?

1. init method will not be called

2. The addSubview method will be called at some time

3. Call when bounds change

4. The layoutSubviews method of scrollView is called when scrollView scrolls (so complex logic is not recommended in the layoutSubviews method of scrollView)

5. Call when rotating equipment

6. Call when subview is removed

See: http://blog.logichigh.com/2011/03/16/when-does-layoutsubviews-get-called/

121. Let UILabel change lines at specified places

// The newline character is \ n. Add the symbol where the newline is needed, such as 
label.numberOfLines = 0;
label.text = @"here\n Line feed";

122. Shake-and-shake function

1. Open the shake-and-shake function

[UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;

2. Make the controller that needs to be shaken the first responder

[self becomeFirstResponder];

3. Implement the following methods

// Begin to shake
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
// Cancel shaking
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
// End of shaking
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event

123. Get picture size

CGFloat imageWidth = image.size.width;
CGFloat imageHeight = imageWidth * image.scale;

124. Get the coordinates of view on the whole window

// The position of (0,0) points on v on toView
CGPoint point = [v convertPoint:CGPointMake(0, 0) toView:[UIApplication sharedApplication].windows.lastObject];
//perhaps
CGPoint point = [v.superview convertPoint:v.frame.origin toView:[UIApplication sharedApplication].windows.lastObject];

125. Submitting App Store Audit Procedure Limitations

The uncompressed size of your application must be less than 4 GB. Each Mach-O executable (such as appname.app/appname) cannot exceed these limits: for applications with Minimum OS Version less than 7.0, the total number of all parts in the TEXT binary file is up to 80 MB. For applications from Minimum OS Version 7.x to 8.x: TEXT has a maximum of 60 MB per fragment of each architecture fragment in a binary file. For applications with Minimum OS Version 9.0 or higher: _TEXT binary file, the total number of all parts is up to 500 MB. See: iTunes Connect Developer's Guide

126. Modify the font size of UISegmented Control

[segment setTitleTextAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15.0f]} forState:UIControlStateNormal];

127. Pop up the UIAlert Controller dialog box in a place other than ViewController

//  It's better to draw up 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];

128. Get the controller to which a view belongs

// view classification method
- (UIViewController *)belongViewController {
    for (UIView *next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

129, UIImage and base64 Interchange

// view classification method
- (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];
}

130. UIWebView Settings Background Transparency

[webView setBackgroundColor:[UIColor clearColor]];
[webView setOpaque:NO];

131. Judge whether 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]) {
    // Today
}

132. Setting the color of tableView partition line

[self.tableView setSeparatorColor:[UIColor myColor]];

133. Setting Screen Direction

[[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeLeft) forKey:@"orientation"];

134. Compare the two colors

- (BOOL)isEqualToColor:(UIColor *)otherColor {
    CGColorSpaceRef colorSpaceRGB = CGColorSpaceCreateDeviceRGB();
6
    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 );
6
            UIColor *color = [UIColor colorWithCGColor:colorRef];
            CGColorRelease(colorRef);
            return color;            
        } else
            return color;
    };
6
    UIColor *selfColor = convertColorToRGBSpace(self);
    otherColor = convertColorToRGBSpace(otherColor);
    CGColorSpaceRelease(colorSpaceRGB);
    return [selfColor isEqual:otherColor];
}

135, tableViewCell partition line top to top

- (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];
}

136. Do not allow the view of the controller to be stretched or compressed with the xib of the controller

self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

137. cocoaPods error: [!] Unable to add a source with url https://github.com/CocoaPods/Specs.git named master-1.

You can try adding it manually in ~/.cocoapods/repos or via pod repo add.

Solution: This is because another Xcode is installed in the computer and cocoapods can't find a path.

Execute sudo xcode-select-switch/Applications/Xcode.app on the terminal.

138. ERROR: While executing gem appears when installing cocoapods. (Errno:: EPERM)

Operation not permitted - /usr/bin/pod

Solution: Perform sudo gem install-n/usr/local/bin cocoapods directly at the terminal

139. Increase the chrysanthemum of network requests in the status bar, similar to the chrysanthemum of the status bar when safari loads a web page

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

140. Check whether a rect contains a point

// Is point in rect?
BOOL isContains = CGRectContainsPoint(rect, point);

141. Let UILabel automatically set the best font at the specified width

label.adjustsFontSizeToFitWidth = YES;

142. Keep an image in an album

UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

perhaps

#import
[[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);
        }
    }];

143. Modify 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();

144. Add dotted borders for 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];

145. Open or disable replication, cutting, selection, full selection and other functions in UITextView

// Inheriting UITextView overrides this method
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
// Return NO to disable, YES to open
    // paste
    if (action == @selector(paste:)) return NO;
    // shear
    if (action == @selector(cut:)) return NO;
    // copy
    if (action == @selector(copy:)) return NO;
    // Choice
    if (action == @selector(select:)) return NO;
    // Select All
    if (action == @selector(selectAll:)) return NO;
    // delete
    if (action == @selector(delete:)) return NO;
    // share
    if (action == @selector(share)) return NO;
    return [super canPerformAction:action withSender:sender];

Topics: Mobile network xcode iOS