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!