NSPredicate as a constraint resolver?

I am working on a project that includes a slightly more complex dynamic layout of interface elements than what I'm used to. I always feel the stupid writing of complex code that checks if such-and-such-and-such is close and in this case moves it in% in any direction, etc. This is simply not how programming should be done. Programming should be as declarative as possible!

Precisely because what I'm going to do is pretty simple, I thought it was a good opportunity to try something new, and I thought about using NSPredicate as a simple constraint NSPredicate . So far, I have used NSPredicate for very simple tasks, but I know that it is capable of much more.

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

I will give a very simple example to answer something specific. How to use NSPredicate to address the following limitations:

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

("viewB should be horizontally aligned at 300 if its left edge does not fall 20 pixels from the right edge of viewB, in which case viewA the left edge should remain fixed at 20 pixels to the right of the right edge of viewB and see the horizontal center, pull to the right. ")

viewA.rightEdge and viewB.width are subject to change, and these are "input variables".

EDIT: any solution would probably need to use the NSExpression method -(id)expressionValueWithObject:(id)object context:(NSMutableDictionary *)context . This answer matters.

+4
source share
2 answers

Solving simple linear equations with NSPredicate (and NSExpression) is a breeze, but moving from there to solving arbitrary sets of constraints (aka Linear Programming) is still a big step. The most promising way forward is to do what Chris Hanson offers and updates his BDRuleEngine , Fun project for a rainy day.

0
source

Cocoa predicates are essentially a kind of SQL for Cocoa. Most of their authority lies in their ability to search for strings and comparisons and does not have additional (useful) possibilities regarding what you are trying to do, (as far as I can tell) numerical comparisons. I don’t think what they do for very convenient code.

Regular Boolean expressions are functionally equivalent to Cocoa predicates, and you can rearrange them and assign them using some beautifully named variables.

 if (viewAIs20PixelsAway && viewBIs30PixelsAway) { [viewA moveToPositionA]; } else ... 

(A very simple example ... I could come up with something better.)

In addition, you can remove them in the method and evaluate them as if you were doing with NSPredicate.

+1
source

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


All Articles