Built-in block when creating a structure

This is for learning =) I understand that functions, methods and blocks can be declared and then called. I'm just trying to understand the blocks better.

This is the basic idea of ​​what I want to do.

CGRectMake(100,^CGFloat(){return 1.0f;},100,100); 

The compiler does not see the return value of the block and instead sees the block itself as a value, which leads to an error. I tried several ways to drop the block, but could not find a solution.

Is there a way to do this, and if so, how? If not, is there another way to make an inline function with a return value?

Edit Here is a sample code that I use based on the correct answer of the first example.

 valueLabelMin.frame = CGRectMake(0, ^CGFloat(){ if (CGRectGetMaxY(dateRangeStartLabel.frame)) { return CGRectGetMaxY(dateRangeStartLabel.frame)-20; }else{ return self.bounds.size.height-20; } }(), 50, 20); 

Edit 2 This is slightly different from the context of the original question, but demonstrates its significance in a context that I always appreciate when reading questions.

This sample code changes the frame of some UILabels based on conditions, is optionally animated, and executes a termination block.

Please note that each setFrame shortcut is called only once, which leads to very manageable code = D Needles, to say the β€œbefore” version was such a mess, I can’t force myself to turn it on.

 - (void)updateValueRangeLabels:(BOOL)animated completion:(void(^)(void))completion { void (^setLabelFrames)() = ^() { valueLabelMax.frame = CGRectMake(^CGFloat(){if(_showValueRange){return 0;}else{return -50;}}(), CGRectGetMaxY(titleLabel.frame), 50, 20); valueLabelMid.frame = CGRectMake(^CGFloat(){if(_showValueRange){return 0;}else{return -50;}}(), CGRectGetMaxY(titleLabel.frame) + (self.bounds.size.height - CGRectGetMaxY(titleLabel.frame) - CGRectGetMinY(dateRangeStartLabel.frame) - 20)/2, 50, 20); valueLabelMin.frame = CGRectMake(^CGFloat(){if(_showValueRange){return 0;}else{return -50;}}(), ^CGFloat(){if(_showDateRange){return CGRectGetMinY(dateRangeStartLabel.frame)-20;}else{return self.bounds.size.height - 20;}}(), 50, 20); }; if (animated) { [UIView animateWithDuration:0.3 animations:^{ setLabelFrames(); }completion:^(BOOL finished){ completion(); }]; }else{ setLabelFrames(); completion(); } } 

The blocks are awesome!

+4
source share
2 answers

Rate this, for example:

 CGRect r = CGRectMake(100,^CGFloat(){return 1.0f;}(),100,100); ^^ 

Another example: introducing a parameter:

 // creates a CGRect with all values set to the parameter (12 in this example) CGRect r = ^CGRect(CGFloat p){return (CGRect){p,p,p,p};}(12); 
+2
source

Normal

 CGRect frame = view.frame; frame.origin.x = 12; view.frame = frame: 

round brackets

 view.frame = (CGRect frame = view.frame; frame.origin.x = 12; frame); 

Block

 view.frame = ^{CGRect frame = view.frame; frame.origin.x = 12; return frame; }(); 
0
source

Source: https://habr.com/ru/post/1482530/


All Articles