Post

Miscellaneous Notes

Miscellaneous iOS notes

Miscellaneous Notes

It has been a long time since I last updated the blog, because the project has been a bit busy.

Back to the point: over nearly a year of development work, I have been recording things I learned using Evernote. This is indeed a good learning habit. However, Evernote does not support Markdown, and there are many ways online to save notes into Evernote in Markdown format. At the moment, I use MaKeFeiXiang, which is quite convenient, but the professional version is paid.

Below are some uncategorized miscellaneous notes from the past two years. Some of them may be helpful.

Joining an Array into a String

1
2
3
NSArray *array=[[NSArray alloc]initWithObjects:@"apple",@"banana",@"strawberry", @"pineapple", nil];
NSString *newString=[array componentsJoinedByString:@","];    
NSLog(@"%@", newString);
1
2013-10-29 15:38:23.372 Nurse[4001:c07] apple,banana,strawberry,pineapple

Splitting a String into an Array

1
2
3
4
5
- (void)viewDidLoad
  {
    NSString *a = [[NSString alloc] initWithString : @"winter melon, watermelon, dragon fruit, big head, puppy" ];
    NSArray *b = [a componentsSeparatedByString:@","];
  }

Getting RGB Values from UIColor

1
2
3
4
5
CGFloat R, G, B;
const CGFloat *components = CGColorGetComponents(color.CGColor);
R = components[0];
G = components[1];
B = components[2];

Anti-Aliasing

Sometimes, after an image is rotated, it may show obvious aliasing.

Solution: add a key named UIViewEdgeAntialiasing to the project’s plist file and set it to YES, but this may have a serious impact on performance.

Apple’s explanation:

Use antialiasing when drawing a layer that is not aligned to pixel boundaries. This option allows for more sophisticated rendering in the simulator but can have a noticeable impact on performance.

Simple solution: add a 1-pixel transparent border around the original image.


Screen Capture

After iOS 7:

1
2
3
4
5
6
UIGraphicsBeginImageContextWithOptions(_sourceViewController.view.frame.size, YES, 0.0);
[self.sourceViewController.view.window drawViewHierarchyInRect:_sourceViewController.view.frame afterScreenUpdates:NO];
UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();


Hiding the Keyboard by Tapping Anywhere on the Screen

Override this in the view controller:

1
2
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;

Method

1
2
3
4
5
6
7
  -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    [super touchesBegan:touches withEvent:event];

    [self.view endEditing:YES];

  }

Adding a Tap Gesture to a View Containing a UITableView

If you add a tap gesture to a view containing a UITableView, that tap gesture will block the UITableView’s

1
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;

You can use the Delegate method of UIGestureRecognizer:

1
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer;

Cancel the gesture when the tap occurs inside the UITableView.

1
2
3
4
5
6
7
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    CGPoint point = [gestureRecognizer locationInView:self];
    if(CGRectContainsPoint(menuTableView.frame, point)){
      return NO;
    }
    return YES;
  }

The simpler solution is to set the tap gesture’s cancelsTouchesInView to NO.

1
singleTap.cancelsTouchesInView = NO;

URLWithString: Returns nil

Solution

1
2
NSString *tempString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:tempString];

Checking Whether a String Contains Chinese Characters

1
2
3
NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:@"[\u4e00-\u9fa5]" options:0 error:nil];
// Return the number of Chinese characters in numberOfMatches
NSUInteger numberOfMatches = [regularExpression numberOfMatchesInString:string options:0 range:NSMakeRange(0, [string length])];

Converting Degrees to Radians

#import <GLKit/GLKit.h>

1
float GLKMathDegreesToRadians(float degrees)

Quickly Locating a Cell

Use a subview inside the cell, in this example a button.

1
NSIndexPath *path = [_collectionView indexPathForItemAtPoint:[button convertPoint:CGPointZero toView:self.collectionView]];

Works for UITableView (with different APIs) and UICollectionView.


Checking Whether One View Is a Subview of Another

1
- (BOOL)isDescendantOfView:(UIView *)view;

Fixing %d and %u Warnings on 64-bit

1
2
3
4
5
6
7
# if __LP64__
# define NSI "ld"
# define NSU "lu"
# else
# define NSI "d"
# define NSU "u"
# endif

Usage

1
2
NSInteger row = 2;
NSLog(@"i=%"NSI@" other text", row);

The ?: Syntax

1
NSLog(@"%@", @"a" ?: @"b"); // @"a"

If the condition is true, it returns the message receiver on the left side of ?:, which here is @"a". Common usage:

1
cell.titleLabel.text = self.name ?:nil;

Opening the System Settings Screen (iOS 8 Only)

1
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];

Opening the App Store (iOS 7 and Later)

Open the product details page.

1
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/app/idxxxxxx"]];

Open the product review page.

1
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=xxxxxx&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8"]];

xxxxx is the Apple ID.


Removing the One-Pixel Bottom Line of UINavigationBar

1
2
[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];

Restore

1
2
[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = nil;

Determining Gesture Direction

  • Vertical
1
2
3
  CGPoint velocity = [sender velocityInView:self];

  BOOL isVerticalGesture = fabsf(velocity.y) >= fabsf(velocity.x);
  • Horizontal
1
2
  CGPoint velocity = [self.panGestureRecognizer velocityInView:self.panGestureRecognizer.view];
  BOOL isHorizontalGesture = fabs(velocity.y) <= fabs(velocity.x);

Scrolling a UIScrollView to the Top

1
self.tableView.contentOffset = CGPointMake(0, 0 - self.tableView.contentInset.top);

Disabling Third-Party Keyboards in the App

Add this in AppDelegate:

1
2
3
4
5
6
- (BOOL)application:(UIApplication *)application shouldAllowExtensionPointIdentifier:(NSString *)extensionPointIdentifier {
    if ([extensionPointIdentifier isEqualToString: UIApplicationKeyboardExtensionPointIdentifier]) {
  ​	  return NO;
    }
    return YES;
  }

Formatting File Size

No need to use the very low-level /1024/1024 conversion to MB anymore. Try this instead:

1
NSString *storage = [NSByteCountFormatter stringFromByteCount:size countStyle:NSByteCountFormatterCountStyleFile];
This post is licensed under CC BY 4.0 by the author.