Skip to content

Instantly share code, notes, and snippets.

@MP0w
Created May 4, 2015 17:16
Show Gist options
  • Save MP0w/40d638a6105b55076377 to your computer and use it in GitHub Desktop.
Save MP0w/40d638a6105b55076377 to your computer and use it in GitHub Desktop.
Experimental Auto Layout short syntax (visual format)
// Usage example : [self addConstraintsWithVisualFormat:@"V:|-0-[myAwesomeView]-0-|", self.awesome, nil];
// no need to use underscore for property
// Actually would break with priority annotations but who care! It's just an experiment
// Not using NSDictionaryOfVariableBindings(...) to have easy use also in swift
- (void)addConstraintsWithVisualFormat:(NSString *)formatString,... NS_REQUIRES_NIL_TERMINATION {
va_list args;
va_start(args, formatString);
NSString *pattern = @"\\[(.*?)\\]";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
NSArray *matches = [regex matchesInString:formatString options:0 range:NSMakeRange(0, formatString.length)];
NSAssert(!error, error.description);
if (error || !matches) {
return;
}
NSMutableDictionary *views = [NSMutableDictionary dictionary];
NSInteger idx = 0;
for (id arg = va_arg(args, id); arg != nil; arg = va_arg(args, id)) {
NSString *key = [formatString substringWithRange:[(NSTextCheckingResult *)matches[idx] rangeAtIndex:1]];
views[key] = arg;
idx++;
}
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:formatString options:nil metrics:nil views:views]];
va_end(args);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment