NSPredicate as a constraint solver?

Posted by Felixyz on Stack Overflow See other posts from Stack Overflow or by Felixyz
Published on 2010-03-02T02:26:48Z Indexed on 2010/03/11 19:59 UTC
Read the original article Hit count: 332

I'm working on a project which includes some slightly more complex dynamic layout of interface elements than what I'm used to. I always feel stupid writing complex code that checks if so-and-so is close to such-and-such and in that case move it x% in some direction, etc. That's just not how programming should be done. Programming should be as declarative as possible!

Precisely because what I'm going to do is fairly simple, I thought it would be a good opportunity to try something new, and I thought of using NSPredicate as a simple constraints solver. I've only used NSPredicate for very simple tasks so far, but I know that it capable of much more.

Are there any ideas, experiences, examples, warnings, insights that could be useful here?

I'll give a very simple example so there will be something concrete to answer. How could I use NSPredicate to solve the following constraints:

viewB.xmid = (viewB.leftEdge + viewB.width) / 2
viewB.xmid = max(300, viewA.rightEdge + 20 + viewB.width/2)

("viewB should be horizontally centered on coordinate 300, unless its left edge gets within 20 pixels of viewB's right edge, in which case viewA's left edge should stay fixed at 20 pixels to the right of viewB's right edge and viewA's horizontal center get pushed to the right.")

viewA.rightEdge and viewB.width can vary, and those are the 'input variables'.

EDIT: Any solution would probably have to use the NSExpression method -(id)expressionValueWithObject:(id)object context:(NSMutableDictionary *)context. This answer is relevant.

© Stack Overflow or respective owner

Related posts about constraints

Related posts about cocoa