Skip to content

Instantly share code, notes, and snippets.

@robbdimitrov
Last active August 6, 2020 03:56
Show Gist options
  • Save robbdimitrov/7513329 to your computer and use it in GitHub Desktop.
Save robbdimitrov/7513329 to your computer and use it in GitHub Desktop.
Useful iOS and Objective-C snippets

iOS and Objective-C snippets

Move content from underneath the navigationBar (iOS 7)

if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) {
    [self setEdgesForExtendedLayout:UIRectEdgeRight|UIRectEdgeBottom|UIRectEdgeLeft];
}

Change the color of the back arrow in navigationBar (iOS 7)

[[UINavigationBar appearance] setTintColor:[UIColor lpl_iconsColor]];

Remove navigationBar shadow

[[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];

Change the alpha value of UINavigationBar elements

- (void)updateBarButtonItemsAlpha:(CGFloat)alpha {
    [self.navigationItem.leftBarButtonItems enumerateObjectsUsingBlock:^(UIBarButtonItem* item, NSUInteger i, BOOL *stop) {
        item.customView.alpha = alpha;
    }];
    [self.navigationItem.rightBarButtonItems enumerateObjectsUsingBlock:^(UIBarButtonItem* item, NSUInteger i, BOOL *stop) {
        item.customView.alpha = alpha;
    }];
    self.navigationItem.titleView.alpha = alpha;
    self.navigationController.navigationBar.tintColor = [self.navigationController.navigationBar.tintColor colorWithAlphaComponent:alpha];
}

Init custom view from xib file

- (id)init {
    NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self.class) owner:self options:nil];
    id mainView = [subviewArray objectAtIndex:0];

    if ([mainView isKindOfClass:[self class]]) {
        return mainView;
    }
    return nil;
}

Weak reference pointer to current object

__weak typeof(self) weakSelf = self;

Enable horizontal only gesture recognizer via Ray Wenderlich

#pragma mark - horizontal pan gesture methods
-(BOOL)gestureRecognizerShouldBegin:(UIPanGestureRecognizer *)gestureRecognizer {
    CGPoint translation = [gestureRecognizer translationInView:[self superview]];
    // Check for horizontal gesture
    if (fabsf(translation.x) > fabsf(translation.y)) {
        return YES;
    }
    return NO;
}

Hide the back button title

// Hide the back button title
UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@""
                                                             style:UIBarButtonItemStylePlain
                                                            target:nil
                                                            action:nil];
[self.navigationItem setBackBarButtonItem:backItem];

Set custom icon for back button

UINavigationBar *navigationBarAppearance = [UINavigationBar appearance];
navigationBarAppearance.backIndicatorImage = [[UIImage imageNamed:@"backArrow"]
                                              imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
navigationBarAppearance.backIndicatorTransitionMaskImage = [[UIImage alloc] init];

Create UIImage from UIColor

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

Create UIImage from template UIImage and UIColor

@implementation UIImage (Color)

- (UIImage *)tintWithColor:(UIColor *)tintColor {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
    CGRect drawRect = CGRectMake(0, 0, self.size.width, self.size.height);
    [self drawInRect:drawRect];
    [tintColor set];
    UIRectFillUsingBlendMode(drawRect, kCGBlendModeSourceAtop);
    UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return tintedImage;
}

@end

Create UIColor from existing UIColor and alpha value

+ (UIColor *)color:(UIColor *)color withAlpha:(CGFloat)alpha {
    CGFloat red, green, blue;
    if ([color getRed:&red green:&green blue:&blue alpha:NULL]) {
        return [UIColor colorWithRed:red
                                green:green
                                 blue:blue
                                alpha:alpha];
    }
    return color;
}

Create blurred image from UIImage and blur radius via Bubbly Blog

- (UIImage *)applyBlurOnImage: (UIImage *)imageToBlur withRadius:(CGFloat)blurRadius {
    if ((blurRadius < 0.0f) || (blurRadius > 1.0f)) { blurRadius = 0.5f; }
    
    int boxSize = (int)(blurRadius * 100); boxSize -= (boxSize % 2) + 1;
    
    CGImageRef rawImage = imageToBlur.CGImage;
    
    vImage_Buffer inBuffer, outBuffer;
    vImage_Error error;
    
    void *pixelBuffer;
    
    CGDataProviderRef inProvider = CGImageGetDataProvider(rawImage);
    
    CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);
    
    inBuffer.width = CGImageGetWidth(rawImage);
    inBuffer.height = CGImageGetHeight(rawImage);
    inBuffer.rowBytes = CGImageGetBytesPerRow(rawImage);
    
    inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);
    
    pixelBuffer = malloc(CGImageGetBytesPerRow(rawImage) * CGImageGetHeight(rawImage));
    
    outBuffer.data = pixelBuffer; outBuffer.width = CGImageGetWidth(rawImage);
    
    outBuffer.height = CGImageGetHeight(rawImage);
    
    outBuffer.rowBytes = CGImageGetBytesPerRow(rawImage);
    
    error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
    
    if (error) { NSLog(@"error from convolution %ld", error); }
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate(outBuffer.data, outBuffer.width, outBuffer.height, 8, outBuffer.rowBytes, colorSpace, CGImageGetBitmapInfo(imageToBlur.CGImage));
    
    CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
    UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
    
    //clean up
    CGContextRelease(ctx);
    CGColorSpaceRelease(colorSpace);
    free(pixelBuffer);
    CFRelease(inBitmapData);
    CGImageRelease(imageRef);
    
    return returnImage;
}

Measure execution time for blocks of code

NSDate *start = [NSDate date];
// code...
NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:start];
NSLog(@"Execution Time: %f", executionTime);

Create a static string for notification

// in .h
extern NSString * const RDTimerDidResumeNotification;
// in .m
NSString * const RDTimerDidResumeNotification = @"com.robbdimitrov.appName.RDTimerDidResumeNotification";

Make a navigationBar fully transparent

[self.navigationBar setBackgroundImage:[UIImage new]
                         forBarMetrics:UIBarMetricsDefault];
self.navigationBar.shadowImage = [UIImage new];
self.navigationBar.translucent = YES;

Hide keyboard with scrolling

// In @interface
@property (nonatomic, assign) CGFloat lastContentOffset;

//Scroll view delegate methods
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.tableView == scrollView) {
        if (scrollView.contentOffset.y - self.lastContentOffset < -90) {
            [self.activeField resignFirstResponder];
        }
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (scrollView != self.tableView) {
        return;
    }
    
    self.lastContentOffset = scrollView.contentOffset.y;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.tableView && scrollView.isDragging) {
        if (scrollView.contentOffset.y - self.lastContentOffset < -90) {
            [self.activeField resignFirstResponder];
        }
    }
}

Hide Settings app with the tab for the current app

BOOL canOpenSettings = (&UIApplicationOpenSettingsURLString != NULL);
if (canOpenSettings) {
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    [[UIApplication sharedApplication] openURL:url];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment