1. String GB2312 encoding

  • String GB2312 encoding

    NSString *arrr = @"Test";
    NSStringEncoding gbkEncoding =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSData *adata = [arrr dataUsingEncoding:gbkEncoding];
    Copy the code

2.UIView monopolizes response events

  • A Boolean value that identifies a view exclusive touch event. Setting ‘exclusiveTouch’ to YES in a view causes the window to block other view trigger response events. The default value is NO.

    _button1.exclusiveTouch = YES;
    Copy the code

3. Set the navigation bar

  • Hide the navigation bar
    - (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated]; 
    [self.navigationController setNavigationBarHidden:YES animated:YES]; 
    } 
    - (void)viewWillDisappear:(BOOL)animated {	
    [super viewWillDisappear:animated]; 
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    }
    Copy the code
  • Set the navigation bar to white:
    • Set in plistView controller-based status bar appearance
      1. Plist View Controller-based status bar appearance is set to NOCopy the code
    • Set in the AppDelegate code
      [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
      
      Copy the code

4.OC block is passed as a function parameter

  • Use an enum typedef void (^OnFoolCallback)(NSString *name);

  • Void productFool:(OnFoolCallback)callback;

    typedef void (^OnFoolCallback)(NSString *name);  
    - (void)productFool:(OnFoolCallback)callback;  
        
    [fb productFool:^(NSString *name) {  
        NSLog(@"name = %@", name);  
    }];
    Copy the code

4. When the section of collectionView is refreshed, there will be animation flash

  • Solution: Stop animation:
    [UIView setAnimationsEnabled:NO];
    [self.homeCollectionView performBatchUpdates:^{
        [self.homeCollectionView reloadSections:[NSIndexSet indexSetWithIndex:index]];
    } completion:^(BOOL finished) {
         [UIView setAnimationsEnabled:YES];
     }];
    Copy the code

5. Control data overstepping crash

  • Array out-of-bounds control

    +(void)load{
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            SEL safeSel=@selector(safeObjectAtIndex:);
            SEL unsafeSel=@selector(objectAtIndex:);
            Class myClass = NSClassFromString(@"__NSArrayI");
            Method safeMethod=class_getInstanceMethod (myClass, safeSel);
            Method unsafeMethod=class_getInstanceMethod (myClass, unsafeSel);
            Method_exchangeImplementations(unsafeMethod, safeMethod);
        });
    }
    -(id)safeObjectAtIndex:(NSUInteger)index{
        if (index>(self.count-1)) {
            NSAssert(NO, @"beyond the boundary");
            return nil;
        }
        else{
            return[self safeObjectAtIndex:index]; }}Copy the code

6. Conversion relationship between Pt and Px

  • The conversion relationship between Pt and Px.Pt = (Px / 96.0) * 72.0 Pixel Point

7. Mute sound: SoundName push notification disables sound

  • Set sound mute: soundName, vibrate is also a Souond: kSystemSoundID_Vibrate

  • The code in the background sets the push content

    PushNotificationPayload payLoad =  PushNotificationPayload.fromJSON(message);  
    payLoad.addAlert("IPhone push test www.baidu.com"); // Message content payLoad. AddBadge (count); // The number in the red circle on the iPhone icon payLoad. AddSound ("default"); // Ring tone by defaultCopy the code
  • 2: in-program code

    #import <AudioToolbox/AudioToolbox.h> AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); AudioServicesPlaySystemSound(1007); // Sound file path NSString *path = [[NSBundle mainBundle] pathForResource:@"message" ofType:@"wav"]; // Assemble and play SystemSoundID soundID; NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO]; AudioServicesCreateSystemSoundID((__bridge CFURLRef)filePath, &soundID); AudioServicesPlaySystemSound(soundID); / / voice stop AudioServicesDisposeSystemSoundID (sound id);Copy the code

8. Edit keyboard issues -> Keyboard retraction

  • There is a keyboard, click save, or edit when clicking the keyboard down, the following bug occurs
    "[the App]if we're in the real pre-commit handler we can'T actually add any new fences due to CA restriction"Copy the code
  • Solutions:[self layoutSubviews];

9. Relative position of UI View

  • Gets the position of the point clicked on the event relative to the screen

    • If the click event is the following method (passing UIEvent back as an argument)
      -(void)expandButtonClicked:(id)sender withEvent:(UIEvent*)event  UITouch* touch = [[event touchesForView:btn] anyObject]; CGPoint rootViewLocation = [touch locationInView:[FtAppDelegate shareAppDelegate].rootViewCtrl.view];Copy the code
    • If you want to know the coordinates of one view relative to the screen or another view, you can do the following:
      UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
      CGRect rect=[bView convertRect: bView.bounds toView:window];
      Copy the code

10.UI View removes subviews

  • Remove all subviews with no loop and only one line of code
     [view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    Copy the code

11. After the VM is installed, the vm cannot be repaired for a period of timeVirtualBox

  • The following error message is displayed when the VM is started
    Shjyytxnj Implementation of the USB 2.0 Controller Not found! Because the USB 2.0 controller state is part of the saved VM state, the VM cannot be started. To fix this problem, either install the'Oracle VM VirtualBox Extension Pack' or disable USB 2.0 support in the VM settings.
    
    Note! This error could also mean that an incompatible version of the 'Oracle VM VirtualBox Extension Pack' is installed (VERR_NOT_FOUND).
    Copy the code
  • An incompatible version of Oracle VM VirtualBox Extension Pack was installed
    Download (1) VirtualBox 5.1.12 Platform Packages.\ (2) VirtualBox 5.1.12 Oracle VM VirtualBox Extension Pack https://www.virtualbox.org/wiki/Downloads matches the version and the plugin to SapporoCopy the code

12. Set the textField placeholder color

  • Set the textField placeholder color
    [self.searchtextField setValue:RGB(156, 86, 49) forKeyPath:@"_placeholderLabel.textColor"];
    [self.searchtextField setValue:[UIFont boldSystemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    Copy the code

13. Navbarhiddern, after disappearing, shows some hidden missing bugs,

  • Hidden Animation problem
    @property (nonatomic, assign) BOOL closeNavBarAnimating;
    - (void)viewDidLoad{
        [super viewDidLoad];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chageBool:)
                                                    name:@"closeBarAnimationing" object:nil];
    }
    -(void)viewWillAppear:(BOOL)animated{
        [super viewWillAppear:animated];
        if (self.closeNavBarAnimating) {
            animated = NO;
        }
        [self.navigationController setNavigationBarHidden:YES animated:animated]; } - (void) viewWillDisappear: (BOOL) animated {[super viewWillDisappear: animated]; [self.navigationControllersetNavigationBarHidden:NO animated:animated];
        self.closeNavBarAnimating = NO;    
    }
    -(void)chageBool:(id)sedner{
        self.closeNavBarAnimating = YES;
        
    }
    Copy the code

14.APP starts GIF animation

  • UIImageView and UIImage do not support GIF animation. Use UIWebView to load the GIF and start the animation
    @interface ViewController () @property (weak, nonatomic) IBOutlet UIWebView *webViewBG; @property (weak, nonatomic) IBOutlet UIButton *regBtn; @property (weak, nonatomic) IBOutlet UIButton *loginBtn; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Initialize UIWebView object and add GIF file NSString *filePath = [[NSBundle mainBundle] pathForResource:@"bg" ofType:@"gif"];
        NSData *gif =[NSData dataWithContentsOfFile:filePath];
        [self.webViewBG loadData:gif MIMEType:@"image/gif"textEncodingName:nil baseURL:nil]; self.webViewBG.userInteractionEnabled = NO; / / create a gray mask, improve effect (optional) UIView * filter = [[UIView alloc] initWithFrame: self. The bounds]; filter.backgroundColor = [UIColor blackColor]; Filter. The alpha = 0.5; [self.view addSubview:filter]; Register/login/modify button and button display level [self. View bringSubviewToFront: self. LoginBtn]; [self.view bringSubviewToFront:self.regBtn]; }Copy the code

15.QQ chat bubble style interface

  • Define enumeration to distinguish yourself from others
    typedef enum{
        WPMessageTypeMe=0,
        WPMessageTypeOther=1
    }WPMessageType;
    Copy the code
  • Calculate the width and height of a paragraph of text
    CGSize textMaxSize=CGSizeMake(200, MAXFLOAT);
    NSDictionary *attr1=@{NSFontAttributeName:[UIFont systemFontOfSize:14]};
    CGSize textSize=[message.text boundingRectWithSize:textMaxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attr1 context:nil].size;              
    Copy the code
  • Take a small image as the background and leave the sides unchanged. Stretch the middle and use the following properties. UIEdgeInsets are the area that you stretch, usually the middle point
    UIImage *meBgNor=[UIImage imageNamed:@"chat_send_nor"];
    UIEdgeInsets edge1=UIEdgeInsetsMake(28, 32, 28, 32);
    meBgNor=[meBgNor resizableImageWithCapInsets:edge1 resizingMode:UIImageResizingModeStretch];
    [self.textView setBackgroundImage:meBgNor forState:UIControlStateNormal];
    Copy the code
  • Listen for keyboard pop-up hide
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil]; - (void) changeFrame: (NSNotification *) note {self. View. Superview. BackgroundColor = [UIColor colorWithRed: green 0.9:0.9 Alpha blue: 0.9, 0.9]; CGFloat duration=[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; CGFloat keyboardY=[note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y; CGFloat screenH=[UIScreen mainScreen].bounds.size.height; [UIView animateWithDuration:duration animations:^{ self.view.transform=CGAffineTransformMakeTranslation(0, keyboardY-screenH); }]; }Copy the code
  • The input field is not an inputView of the keyboard, it’s also floating on the view without the keyboard, and when the keyboard pops up you just control the frame of the view, align the bottom
  • Lable adaptive
    label.adjustsFontSizeToFitWidth = YES;
    Copy the code

16. Use CAShapeLayer to realize a control with dynamic volume change similar to wechat voice

  • Layer is a rectangle. MaskToBounds is yes.
  • _dynamicView represents the View of the external contour. _indicateLayer Indicates the Layer that displays content dynamically
    -(void)refreshUIWithVoicePower : (NSInteger)voicePower{
        CGFloat height = (voicePower)*(CGRectGetHeight(_dynamicView.frame)/TOTAL_NUM);
        [_indicateLayer removeFromSuperlayer];
        _indicateLayer = nil;
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, CGRectGetHeight(_dynamicView.frame)-height, CGRectGetWidth(_dynamicView.frame), height) cornerRadius:0];
        _indicateLayer = [CAShapeLayer layer];
        _indicateLayer.path = path.CGPath;
        _indicateLayer.fillColor = [UIColor whiteColor].CGColor;
        [_dynamicView.layer addSublayer:_indicateLayer];
    }
    Copy the code

17. Compare which image UIimageView image is

  • Implement the gesture guide page to switch between the next image and the last one to remove the UIimageView
  • You can also add a tag to the imageView to determine which image it is based on imageData
    NSData *data = UIImagePNGRepresentation(self.guidImageView.image);
        NSData *data1 = UIImagePNGRepresentation([UIImage imageNamed:@"home_bj_yd1"]);
        NSData *data2 = UIImagePNGRepresentation([UIImage imageNamed:@"home_bj_yd2"]);
        NSData *data3 = UIImagePNGRepresentation([UIImage imageNamed:@"home_bj_yd3"]);
    
    if ( [data isEqual:data1]) {
            self.guidImageView.image=[UIImage imageNamed:@"home_bj_yd2"];
        }
    Copy the code

18. Phone size for APP development

  • Start page size
  • Boot page size
  • The size of the introductory image for the AppStore store
    NSLog(@"name: %@", [[UIDevice currentDevice] name]);
    NSLog(@"systemName: %@", [[UIDevice currentDevice] systemName]);
    NSLog(@"systemVersion: %@", [[UIDevice currentDevice] systemVersion]);
    NSLog(@"model: %@", [[UIDevice currentDevice] model]);
    NSLog(@"localizedModel: %@", [[UIDevice currentDevice] localizedModel]);
    Copy the code

19. Click the top notification message error:

  • In the click event, if we don’t write completionHandler (), we might get an error
    Warning: UNUserNotificationCenter delegate received call to -
    userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: but the completion handler was never called.
    
    2017-01-16 15:00:36.045772 JYYinYongBao[1006:326459] Warning: UNUserNotificationCenter delegate received call to -userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: but the completion handler was never called.
    Copy the code

20.Xcode folder drag points

  • Yellow folders, when packing, do not create directories, mainly save program files
    • Materials are not allowed to have the same name
  • The blue folder, when packing, will create a directory, can be divided into directories to store material files
    • The material can have the same name
    • PNG [Grass/Snow/mountain/tomb]
    • Skin for mobile app, / Day/night mode
    • Remember: do not put the program files in the blue folder, the program will leak
  • Bundle:
    • Usually in third party frame material
    • You can drag and drop as a yellow folder while preserving the directory structure
    • Duplicate file names can be avoided