-
Notifications
You must be signed in to change notification settings - Fork 0
/
AutolayoutHelper.m
462 lines (361 loc) · 15.3 KB
/
AutolayoutHelper.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
#import "AutolayoutHelper.h"
#define XT_CONSTRAINT_ERROR @"Invalid extended constraint"
@interface AutolayoutHelper ()
@property(nonatomic, strong) NSMutableDictionary* temporalConstraints;
@property(nonatomic, strong) UIView* strongPointerToView;
@end
@implementation AutolayoutHelper
BOOL displayBackgroundColorsForDebugging = NO;
NSRegularExpression * xtConstraintRegex;
NSDictionary* attributes;
NSDictionary* relations;
+ (void) initialize
{
[self initializeXtConstraintLogic];
}
+ (void)setDisplayBackgroundColorsForDebugging:(BOOL)displayColors {
displayBackgroundColorsForDebugging = displayColors;
}
+ (AutolayoutHelper*)configureView:(UIView*)view subViews:(NSDictionary*)subViews constraints:(NSArray*)constraints
{
return [AutolayoutHelper configureView:view subViews:subViews metrics:nil constraints:constraints];
}
+ (AutolayoutHelper*)configureView:(UIView*)view subViews:(NSDictionary*)subViews metrics:(NSDictionary*)metrics constraints:(NSArray*)constraints
{
return [self configureView:view subViews:subViews metrics:metrics constraints:constraints keepViewStrongly:NO];
}
+ (AutolayoutHelper*)configureView:(UIView*)view subViewLayers:(NSArray*)subViewLayers metrics:(NSDictionary*)metrics constraints:(NSArray*)constraints
{
return [AutolayoutHelper configureView:view subViewLayers:subViewLayers metrics:metrics constraints:constraints keepViewStrongly:NO];
}
+ (AutolayoutHelper*)configureView:(UIView*)view fillWithSubView:(UIView*)v
{
return [self configureView:view subViews:VarBindings(v) constraints:@[@"H:|[v]|", @"V:|[v]|"]];
}
+ (AutolayoutHelper*)configureViewController:(UIViewController*)controller fillWithSubView:(UIView*)v
{
id <UILayoutSupport> top = controller.topLayoutGuide;
id <UILayoutSupport> bottom = controller.bottomLayoutGuide;
return [self configureView:controller.view
subViews:VarBindings(top, v, bottom)
constraints:@[@"H:|[v]|", @"V:[top][v][bottom]"]];
}
+ (AutolayoutHelper*)subViews:(NSDictionary*)subViews constraints:(NSArray*)constraints
{
return [AutolayoutHelper subViews:subViews metrics:nil constraints:constraints];
}
+ (AutolayoutHelper*)subViews:(NSDictionary*)subViews metrics:(NSDictionary*)metrics constraints:(NSArray*)constraints
{
// Here we want to keep the view strongly, because the AutolayoutHelper.view property is weak
return [self configureView:[[UIView alloc] init] subViews:subViews metrics:metrics constraints:constraints keepViewStrongly:YES];
}
+ (AutolayoutHelper*)configureView:(UIView*)view subViews:(NSDictionary*)subViews metrics:(NSDictionary*)metrics constraints:(NSArray*)constraints keepViewStrongly:(BOOL)keepViewStrongly
{
return [AutolayoutHelper configureView:view subViewLayers:@[subViews] metrics:metrics constraints:constraints keepViewStrongly:keepViewStrongly];
}
+ (void)configureScrollView:(UIScrollView*)scrollView contentView:(UIView*)contentView mainView:(UIView*)mainView {
[AutolayoutHelper configureView:scrollView fillWithSubView:contentView];
[mainView addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"H:[contentView(==mainView)]"
options:(NSLayoutFormatOptions)0
metrics:nil
views:VarBindings(contentView, mainView)]];
}
/**
* The methods above end up calling this one
*/
+ (AutolayoutHelper*)configureView:(UIView*)view subViewLayers:(NSArray*)subViewLayers metrics:(NSDictionary*)metrics constraints:(NSArray*)constraints keepViewStrongly:(BOOL)keepViewStrongly
{
AutolayoutHelper* helper = [[AutolayoutHelper alloc] initWithView:view];
if (keepViewStrongly) {
helper.strongPointerToView = view;
}
helper.metrics = metrics;
for (NSDictionary* subViews in subViewLayers) {
[helper addViews:subViews];
}
[helper addConstraints:constraints];
return helper;
}
- (id)initWithView:(UIView*)view
{
self = [super init];
self.view = view;
self.subViews = [[NSMutableDictionary alloc] init];
self.temporalConstraints = [[NSMutableDictionary alloc] init];
return self;
}
- (void)addViews:(NSDictionary*)subViews {
for (NSString* subViewKey in subViews.allKeys) {
UIView* subView = subViews[subViewKey];
[self addView:subView withKey:subViewKey];
}
}
- (void)addView:(UIView*)subView withKey:(NSString *)subViewKey
{
self.subViews[subViewKey] = subView;
// Ignore layout guides, just keep then in subViews dictionary
if ([subView conformsToProtocol:@protocol(UILayoutSupport)]) {
return;
}
subView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:subView];
if (displayBackgroundColorsForDebugging) {
subView.backgroundColor = [AutolayoutHelper getRandomColorWithAlpha:0.4];
}
}
+ (UIColor*)getRandomColorWithAlpha:(CGFloat)alpha
{
u_int32_t red = arc4random_uniform(256);
u_int32_t green = arc4random_uniform(256);
u_int32_t blue = arc4random_uniform(256);
return [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:alpha];
}
- (void)addViews:(NSDictionary*)subViews constraints:(NSArray*)constraints {
[self addViews:subViews];
[self addConstraints:constraints];
}
- (void)removeViews:(NSDictionary*)subViews {
[self removeViewsWithKeys:subViews.allKeys];
}
- (void)removeViewsWithKeys:(NSArray*)viewKeys {
for (NSString* viewKey in viewKeys) {
UIView* subView = self.subViews[viewKey];
[subView removeFromSuperview];
[self.subViews removeObjectForKey:viewKey];
}
}
- (void)addConstraints:(NSArray*)constraints
{
[self addConstraints:constraints priority:PRIORITY_DEFAULT];
}
- (void)addConstraints:(NSArray*)constraints priority:(UILayoutPriority)priority
{
for (NSString* constraint in constraints) {
[self addConstraint:constraint priority:priority];
}
}
- (NSArray*)addConstraint:(NSString*)constraint
{
return [self addConstraint:constraint priority:PRIORITY_DEFAULT];
}
- (NSArray*)addConstraint:(NSString*)constraint priority:(UILayoutPriority)priority
{
NSArray *constraints = [self parseConstraint:constraint];
if (priority != PRIORITY_DEFAULT) {
for (NSLayoutConstraint* c in constraints) {
c.priority = priority;
}
}
[self.view addConstraints:constraints];
return constraints;
}
- (NSArray*)parseConstraint:(NSString *)constraint
{
if ([constraint hasPrefix:XT_CONSTRAINT_SYMBOL])
{
return [self parseXtConstraint:constraint];
} else {
// Normal VFL constraint
return [NSLayoutConstraint constraintsWithVisualFormat:constraint
options:(NSLayoutFormatOptions) 0
metrics:self.metrics
views:self.subViews];
}
}
- (void)setConstraints:(NSArray*)constraints forKey:(NSString*)key {
[self setConstraints:constraints priority:PRIORITY_DEFAULT forKey:key];
}
- (void)setConstraints:(NSArray*)constraints priority:(UILayoutPriority)priority forKey:(NSString*)key {
// Remove previously added constraints for that key
NSArray* constraintsToRemove = self.temporalConstraints[key];
if (constraintsToRemove.count > 0) {
[self.view removeConstraints:constraintsToRemove];
[self.temporalConstraints removeObjectForKey:key];
}
// Add new constraints and store them
NSMutableArray* addedConstraints = [[NSMutableArray alloc] init];
for (NSString* constraint in constraints) {
NSArray* resultingConstraints = [self addConstraint:constraint priority:priority];
[addedConstraints addObjectsFromArray:resultingConstraints];
}
self.temporalConstraints[key] = addedConstraints;
}
#pragma mark - xt constaints
+ (void)initializeXtConstraintLogic
{
[self initializeXtConstraintRegex];
attributes = @{
@"left" : @(NSLayoutAttributeLeft),
@"right" : @(NSLayoutAttributeRight),
@"top" : @(NSLayoutAttributeTop),
@"bottom" : @(NSLayoutAttributeBottom),
@"leading" : @(NSLayoutAttributeLeading),
@"trailing" : @(NSLayoutAttributeTrailing),
@"width" : @(NSLayoutAttributeWidth),
@"height" : @(NSLayoutAttributeHeight),
@"centerX" : @(NSLayoutAttributeCenterX),
@"centerY" : @(NSLayoutAttributeCenterY),
@"baseline" : @(NSLayoutAttributeBaseline)
};
relations = @{
@"==" : @(NSLayoutRelationEqual),
@">=" : @(NSLayoutRelationGreaterThanOrEqual),
@"<=" : @(NSLayoutRelationLessThanOrEqual)
};
}
+ (void)initializeXtConstraintRegex
{
NSError* error = nil;
// C identifier
NSString* identifier = @"[_a-zA-Z][_a-zA-Z0-9]{0,30}";
// VIEW_KEY.ATTR or (use "superview" as VIEW_KEY to refer to superview)
NSString* attr = [NSString stringWithFormat:@"(%@)\\.(%@)", identifier, identifier];
// Relations taken from NSLayoutRelation
NSString* relation = @"([=><]+)";
// float number e.g. "12", "12.", "2.56"
NSString* number = @"\\d+\\.?\\d*";
// Value (indentifier or number)
NSString* value = [NSString stringWithFormat:@"(?:(?:%@)|(?:%@))", identifier, number];
// e.g. "*5" or "/ 27.3" or "* 200"
NSString* multiplier = [NSString stringWithFormat:@"([*/]) *(%@)", value];
// e.g. "+ 2." or "- 56" or "-7.5"
NSString* constant = [NSString stringWithFormat:@"([+-]) *(%@)", value];
NSString* pattern = [NSString stringWithFormat:@"^%@: *%@ *%@ *%@ *(?:%@)? *(?:%@)?$",
XT_CONSTRAINT_SYMBOL, attr, relation, attr, multiplier, constant];
xtConstraintRegex = [NSRegularExpression
regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:&error];
}
- (NSArray*)parseXtConstraint:(NSString*)constraint
{
NSArray* results = [xtConstraintRegex matchesInString:constraint
options:0
range:NSMakeRange(0, constraint.length)];
if (results.count != 1) {
[self throwInvalidConstraint:constraint];
}
NSTextCheckingResult* match = results[0];
// I think this won't happen if the regex is right, but check for debugging
if (match.numberOfRanges != 10) {
[self dumpMatch:match forString:constraint];
[self throwInvalidConstraint:constraint];
}
// item1.attr1 relation item2.attr2 factor constant
// e.g. v1.leading == v2.centerX / 2 + 10
NSString* item1Key = [constraint substringWithRange:[match rangeAtIndex:1]];
NSString* attr1Str = [constraint substringWithRange:[match rangeAtIndex:2]];
NSString* relationStr = [constraint substringWithRange:[match rangeAtIndex:3]];
NSString* item2Key = [constraint substringWithRange:[match rangeAtIndex:4]];
NSString* attr2Str = [constraint substringWithRange:[match rangeAtIndex:5]];
id item1 = [self findViewFromKey:item1Key];
id item2 = [self findViewFromKey:item2Key];
NSLayoutAttribute attr1 = [self parseAttribute:attr1Str];
NSLayoutAttribute attr2 = [self parseAttribute:attr2Str];
NSLayoutRelation relation = [self parseRelation:relationStr];
// Default multiplier is 1
CGFloat multiplier = 1;
if ([match rangeAtIndex:6].location != NSNotFound)
{
NSString* operation = [constraint substringWithRange:[match rangeAtIndex:6]];
NSString* multiplierValue = [constraint substringWithRange:[match rangeAtIndex:7]];
multiplier = [self getFloatFromValue:multiplierValue];
// If division, invert factor
if ([operation isEqualToString:@"/"]) {
multiplier = 1/multiplier;
}
}
// Default constant is 0
CGFloat constant = 0;
if ([match rangeAtIndex:8].location != NSNotFound)
{
NSString* operation = [constraint substringWithRange:[match rangeAtIndex:8]];
NSString* constantValue = [constraint substringWithRange:[match rangeAtIndex:9]];
constant = [self getFloatFromValue:constantValue];
// If subtraction, negate constant
if ([operation isEqualToString:@"-"]) {
constant = -constant;
}
}
NSLayoutConstraint* c =
[NSLayoutConstraint constraintWithItem:item1
attribute:attr1
relatedBy:relation
toItem:item2
attribute:attr2
multiplier:multiplier
constant:constant];
return @[c];
}
- (float)getFloatFromValue:(NSString*)value
{
if ([self stringStartsWithAlphaOrUnderscore:value]) { // if so, must be a metric identifier
NSNumber* metric = self.metrics[value];
if (metric) {
return [metric floatValue];
} else {
NSString* reason = [NSString stringWithFormat:@"Metric `%@` was not provided", value];
@throw([NSException exceptionWithName:XT_CONSTRAINT_ERROR reason:reason userInfo:nil]);
}
} else {
return [value floatValue];
}
}
- (BOOL)stringStartsWithAlphaOrUnderscore:(NSString*)value
{
unichar c = [value characterAtIndex:0];
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';
}
- (id)findViewFromKey:(NSString*)key
{
if ([key isEqualToString:@"superview"]) {
return self.view;
} else {
id view = self.subViews[key];
if (view) {
return view;
} else {
NSString* reason = [NSString stringWithFormat:@"No view was added with key `%@`", key];
@throw([NSException exceptionWithName:XT_CONSTRAINT_ERROR reason:reason userInfo:nil]);
}
}
}
- (NSLayoutAttribute)parseAttribute:(NSString*)attrStr
{
NSNumber* value = attributes[attrStr];
if (value) {
return (NSLayoutAttribute) [value intValue];
} else {
NSString* reason = [NSString stringWithFormat:@"Attribute `%@` is not valid. Use one of: %@", attrStr, [attributes allKeys]];
@throw([NSException exceptionWithName:XT_CONSTRAINT_ERROR reason:reason userInfo:nil]);
}
}
- (NSLayoutRelation)parseRelation:(NSString*)relationStr
{
NSNumber* value = relations[relationStr];
if (value) {
return (NSLayoutRelation) [value intValue];
} else {
// This won't happen since the regex only matches if the relation is right
NSString* reason = [NSString stringWithFormat:@"Relation `%@` is not valid. Use one of: %@", relationStr, [relations allKeys]];
@throw([NSException exceptionWithName:XT_CONSTRAINT_ERROR reason:reason userInfo:nil]);
}
}
- (void)throwInvalidConstraint:(NSString*)constraint
{
[NSException raise:XT_CONSTRAINT_ERROR
format:@"%@: %@", XT_CONSTRAINT_ERROR, constraint];
}
-(void)dumpMatch:(NSTextCheckingResult*)match forString:(NSString*)str
{
for (NSUInteger i=0; i<match.numberOfRanges; i++) {
NSRange range = [match rangeAtIndex:i];
if (range.location != NSNotFound) {
NSLog(@"Range %lu: %@", (unsigned long)i, [str substringWithRange:range]);
} else {
NSLog(@"Range %lu NOT FOUND", (unsigned long)i);
}
}
}
@end