Created
May 4, 2015 17:16
-
-
Save MP0w/40d638a6105b55076377 to your computer and use it in GitHub Desktop.
Experimental Auto Layout short syntax (visual format)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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