1. Set the font color and size of the navigation bar title
Method 1: (Custom view method, the general public will also adopt this way)
To add a titleView to the navigation, you can use a label, and then set the background color of the label to be transparent. It's easy to set the font or something.
//Custom Title View UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)]; titleLabel.backgroundColor = [UIColor grayColor]; titleLabel.font = [UIFont boldSystemFontOfSize:20]; titleLabel.textColor = [UIColor greenColor]; titleLabel.textAlignment = NSTextAlignmentCenter; titleLabel.text = @"Journalism"; self.navigationItem.titleView = titleLabel;
Method 2: (It is also possible to modify the size and color of the file directly in the title displayed by default)
[self.navigationController.navigationBar setTitleTextAttributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:19], NSForegroundColorAttributeName:[UIColor redColor] } ]
2. The bug of adding the same child control to multiple containers
[someView addSubView:sbView];
Before being added to the parent view someView, if sbView has been loaded by otherView, the above code will first say that sbView is remove d from otherView and loaded into someView.
So it is impossible for a view to be loaded as a sub-view by more than two views at the same time.
3. Return to Root Controller
- (void)dismissToRootViewController:(UIViewController *)viewController{ if (viewController.presentingViewController == nil) { [viewController.navigationController popToRootViewControllerAnimated:NO]; }else{ UIViewController *vc = viewController.presentingViewController; while (vc.presentingViewController != nil) { vc = vc.presentingViewController; } [vc dismissViewControllerAnimated:NO completion:nil]; } }
4. Getting information about the location of the photograph
- (NSDictionary *)metadata { return self.asset.defaultRepresentation.metadata; } - (CLGeocoder *)geoC { if(!_geoC){ _geoC = [[CLGeocoder alloc] init]; } return _geoC; } - (void)addressInit{ // Getting Location Information NSDictionary *metadata = [self metadata]; NSDictionary *GPSDict=[metadata objectForKey:(NSString*)kCGImagePropertyGPSDictionary]; // Longitude and Latitude CLLocationDegrees latitude = [[GPSDict objectForKey:@"Latitude"] doubleValue]; CLLocationDegrees longitude = [[GPSDict objectForKey:@"Longitude"] doubleValue]; CLLocation *loc = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude]; WEAKSELF // Anti-geocoding [self.geoC reverseGeocodeLocation:loc completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) { CLPlacemark *pl = [placemarks firstObject]; if(error == nil){ NSString *str = [NSString stringWithFormat:@"%@%@%@",pl.locality, pl.subLocality, pl.name]; weakSelf.address = str; } else{ weakSelf.address = @""; } }]; }
5. Random Numbers and Random Colors
There is an arc4random () function in Objective-C to generate random numbers without seeds.
However, the range of random numbers generated by this function is relatively large, so it is a bit troublesome to restrict the random values by modular algorithm.
A more convenient random number function arc4random_uniform(x)
It can be used to generate random numbers in the range of 0 to (x-1) without modularization.
If you want to generate 1-x random numbers, you can write as follows: arc4random_uniform(x)+1
Random color:
#define random(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0alpha:(a)/255.0] #define randomColor random(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256)) [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1];
6. Exit app
AppDelegate *app = [UIApplication sharedApplication].delegate; UIWindow *window = app.window; [UIView animateWithDuration:0.4f animations:^{ window.alpha = 0; CGFloat y = window.bounds.size.height; CGFloat x = window.bounds.size.width / 2; window.frame = CGRectMake(x, y, 0, 0); } completion:^(BOOL finished) { exit(0); }];
7. Remove Navigation Bar Button
UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd]; button.frame = CGRectMake(0, 0, 30, 30); UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button]; self.navigationItem.leftBarButtonItem = barButton; #if 0 //First self.navigationItem.leftBarButtonItem = nil; #else //Second [self.navigationController.navigationBar.subviews.lastObject setHidden:YES]; #endif
8. Hidden Navigation Bar Underlines
// 1)statement UIImageView variable,Storage bottom crossbar @implementation MyViewController { UIImageView *navBarHairlineImageView; } // 2)stay viewDidLoad To join: navBarHairlineImageView = [self findHairlineImageViewUnder:navigationBar] // 3) - (UIImageView *)findHairlineImageViewUnder:(UIView *)view { if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) { return (UIImageView *)view; } for (UIView *subview in view.subviews) { UIImageView *imageView = [self findHairlineImageViewUnder:subview]; if (imageView) { return imageView; } } return nil; } // Finally, in the viewWillAppear,viewWillDisappear Intermediate treatment - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; navBarHairlineImageView.hidden = YES; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; navBarHairlineImageView.hidden = NO; } WEAKSELF static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ [weakSelf.navigationController.navigationBar.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { if ([obj isKindOfClass:NSClassFromString(@"_UIBarBackground")]) { [obj.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { if ([obj isKindOfClass:[UIImageView class]]) { [obj setHidden:YES]; } }]; } }]; });
9. translucent and controller.
translucent = NO;
translucent = YES;
10. Disabling Third Party Input Method
- (BOOL)application:(UIApplication *)application shouldAllowExtensionPointIdentifier:(NSString*)extensionPointIdentifier { return NO; }
11. UIView Screen Capture
/* UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0); CGContextRef context = UIGraphicsGetCurrentContext(); // Render the view [view.layer renderInContext:context]; // Get the image from the context UIImage *renderedImage = UIGraphicsGetImageFromCurrentImageContext(); // Cleanup the context you created UIGraphicsEndImageContext(); return renderedImage; */ + (UIImage *)snapShotFrom:(UIView *)view{ // avoid frame by nil Cause anomalies if (CGRectIsEmpty(view.frame)) { return nil; } UIGraphicsBeginImageContextWithOptions(view.frame.size, YES, 0.0); if ([view respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) { [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES]; } else{ // High memory footprint Cause anomalies [view.layer renderInContext:UIGraphicsGetCurrentContext()]; } UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }
Collapse when view switching is fast
The crash was discovered by using a while loop for 100 consecutive screenshots of webview s, and it was EXE_BAD_ACCESS.
The reason is that after Screen Updates is set to YES.
Why does it crash? Because when YES is set, these methods wait until view update is finished, and if view is release d before update is finished, there will be a problem that view can not be found. So NO is needed.
12. Solution of XCODE Debugging without Displaying Variable Value/Pointer Address
1. Ensure that the run in Scheme is set to debug
2.build settings - Search optim to ensure - O0
3.build settings - Search - O 2, change to - g. This is the most pitiful one, which seems to be set to - O2 by default.
13. Compare the two pictures
1. If both images are loaded into resource and the name of the image is known, use imageNamed: Create two UIImage objects, and then compare them with isequal.
2. The two pictures are stored somewhere in the ios sandbox and not loaded into the resource. Compare the data of the two UI Images to see if they are the same.
NSString* file = [dic stringByAppendingPathComponent:path]; UIImage *image = [UIImage imageWithContentsOfFile:file]; NSData *data1 = UIImagePNGRepresentation(image1); NSData *data = UIImagePNGRepresentation(image); if ([data isEqual:data1]) { NSLog(@"is equae"); }
14. UITableView Spacing, Color
It is impossible to change the height of its seperator.
First, we set its sperator to none.
Second, when we build tableview, we use multiple secton s, with only one row per section.
Third, set the height of each section's headerView to the required height.
Fourth, customize the headerView of each section and set the background color of the section to the specified color.
The code is as follows:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, height)]; //height The height set for the designer. view.backgroundColor = [UIColor redColor]; return view; }
15. Real-time detection of UITextField changes
With UISearchBar, when the content of UISearchBar changes dynamically, we can know the change through proxy.
When using UITextField, there is no appropriate proxy function and registration notification is used.
// 1,stay initWithNibName Register the corresponding notification: - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged:) name:UITextFieldTextDidChangeNotification object:_passwordTextField]; } return self; } // 2,Realization textFieldChanged function - (void)textFieldChanged:(id)sender { NSLog(@"current ContentOffset is %@",NSStringFromCGPoint(_contentView.contentOffset)); } // 3,Remember in dealloc Delete the notification. - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil]; }
16. UITextField with Shadows
When UITextView is input, there are shadows under the text. By default, only UILabel has several simple interfaces to set shadows.
As for the shadow of UITextView, it's basically useless. The way to shade the text of UITextView is to set it up through the layer layer layer.
Coding
Remember to add QuartzCore.framework.
View Code
17. First start of judgment procedure
View Code
18. View UUID
1. View the UUID of the xx.app file and enter commands in terminal:
· dwarfdump --uuid xx.app/xx (xx stands for your project name)
2. View the UUID of the xx.app.dSYM file and enter commands in terminal:
·dwarfdump --uuid xx.app.dSYM
3. The first line Incident Identifier in the crash file is the UUID of the crash file.
19. Disabling gestures
<UIGestureRecognizerDelegate> self.navigationController.interactivePopGestureRecognizer.delegate = self; - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{ return NO; }
20. Encoding and Decoding UTF-8 by NSString
// iOS For strings UTF-8 Coding: Output str String UTF-8 format [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; // Decoding: str String with UTF-8 Rule decoding [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
21. Handling of conflict between gesture and tableview events
// stay view Add tag When gesturing,And set tag Proxy for events //Then write the logic according to the specific business scenario.,such as - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch { //Tip:We can print it. touch.view Take a look at the specific clicks view What is the specific name?,Like clicking UITableViewCell Time-responsive View then is UITableViewCellContentView. if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) { //Return to NO Shield gesture events return NO; } return YES; }
22. ScrollView header Hover
- (void)scrollViewDidScroll:(UIScrollView *)scrollView { if (scrollView.contentOffset.y >= 50) { self.header.frame = CGRectMake(0, 0, 375, 35); [self.view addSubview:self.header]; } else { self.header.frame = CGRectMake(0, 50, 375, 35); [self.scrollView addSubview:self.header]; } }
23. Random selection of a font from a device-supported font
// Random selection of fonts from device supported fonts NSString *fontName = @""; NSUInteger count1 = arc4random() % ([UIFont familyNames].count); NSString *familyName = [UIFont familyNames][count1]; NSUInteger count2 = [UIFont fontNamesForFamilyName:familyName].count; fontName = [UIFont fontNamesForFamilyName:familyName][arc4random() % count2];
24. UIFont to CGFontRef
// Establish UIFont Typeface UIFont *font = [UIFont systemFontOfSize:15]; // convert to CGFontRef CFStringRef fontName = (__bridge CFStringRef)font.fontName; CGFontRef fontRef = CGFontCreateWithFontName(fontName);
25. String rescheduling failed.
//You're using the wrong formatter: NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"yyyy"]; NSDate *startDatePlain=[formatter dateFromString:start]; NSDate *endDatePlain=[formatter dateFromString:end]; //You need to use your detailformatter: NSDateFormatter *detailformatter = [[NSDateFormatter alloc] init]; [detailformatter setDateFormat:@"MM/dd/yyyy"]; NSDate *startDatePlain=[detailformatter dateFromString:start]; NSDate *endDatePlain=[detailformatter dateFromString:end]; //You've got the correct format set on detailformatter!