After exposure to the open source project masonry, I am interested in the chained notation of the layout constraints, as follows:
1 2 3 4 5 6 7 8 |
UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10); [view1 mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(superview.mas_top). with .offset(padding.top); //with is an optional semantic filler make.left.equalTo(superview.mas_left). with .offset(padding.left); make.bottom.equalTo(superview.mas_bottom). with .offset(-padding.bottom); make.right.equalTo(superview.mas_right). with .offset(-padding.right); }]; |
Other languages, such as Lua, make it easy to implement chained syntax. But in Objective-c, how to implement the chain-like grammar?
Note: The chained syntax discussed here refers specifically to the point-chaining syntax, which differs from the bracket-linked syntax, such as [[[[[] [[[] [[[]] method2] method3] method4:someparam]. The square brackets link syntax is relatively simpler, and the return value of each method is the sender of the next method.
View masonry source code, at first did not understand, so searched the next StackOverflow, did not find similar problems, then put this issue on the StackOverflow. Here is the address.
Summarize the next, paste the code, do a description.
123456789Ten One A - - the - - - + - + A at - - - - - in - to + - the * $Panax Notoginseng - the + A the + - $ $ - - the -Wuyi the - Wu - About $ - - - A + the - $ the the the the - |
@class ClassB; @interface ClassA : NSObject // 1. 定义一些 block 属性 @property(nonatomic, readonly) ClassA *(^aaa)(BOOL enable); @property(nonatomic, readonly) ClassA *(^bbb)(NSString* str); @property(nonatomic, readonly) ClassB *(^ccc)(NSString* str); @implement ClassA // 2. 实现这些 block 方法,block 返回值类型很关键,影响着下一个链式 - (ClassA *(^)(BOOL))aaa { return ^(BOOL enable) { //code if (enable) { NSLog(@ "ClassA yes" ); } else { NSLog(@ "ClassA no" ); } return self; } } - (ClassA *(^)(NSString *))bbb { return ^(NSString *str)) { //code NSLog(@ "%@" , str); return self; } } // 这里返回了ClassB的一个实例,于是后面就可以继续链式 ClassB 的 block 方法 // 见下面例子 .ccc(@"Objective-C").ddd(NO) - (ClassB * (^)(NSString *))ccc { return ^(NSString *str) { //code NSLog(@ "%@" , str); ClassB* b = [[ClassB alloc] initWithString:ccc]; return b; } } //------------------------------------------ @interface ClassB : NSObject @property(nonatomic, readonly) ClassB *(^ddd)(BOOL enable); - (id)initWithString:(NSString *)str; @implement ClassB - (ClassB *(^)(BOOL))ddd { return ^(BOOL enable) { //code if (enable) { NSLog(@ "ClassB yes" ); } else { NSLog(@ "ClassB no" ); } return self; } } // 最后我们可以这样做 id a = [ClassA new ]; a.aaa(YES).bbb(@ "HelloWorld!" ).ccc(@ "Objective-C" ).ddd(NO) |
How do I implement chained syntax in Objective-c?