Layout: How to use property in visual format

依然范特西╮ 提交于 2019-12-25 12:46:15

问题


I have two classes.

Parent class has a property:

@interface ParentVC

    @property (nonatomic, strong) UIImageView* logoImageView;
@end

So, now, I need to output this view with layout constraints in subclass.

@interface ChildVC : ParentVC
@end

How to correct format string of visual format?

@"V:|-(%i)-[self.logoImageView]" // wrong

I found solution:

UIView* selfLogoImageView = self.logoImageView;

@"V:|-(%i)-[selfLogoImageView]"

But is there any method without new variable?


回答1:


Since you are using the visual format language, you are also using [NSLayoutConstraint constraintsWithVisualFormat:options:metrics:views]. That method expects a dictionary for the views: parameter. Are you using NSDictionaryOfVariableBindings? If so, you don’t have to. You can pass in any old dictionary, as long as it maps your views to names that you use in the visual format string. Incidentally, you can also pass a metrics dictionary, instead of what you are doing with the %i format specifier.

NSDictionary *views = @{ @"logo" : self.logoImageView, // use any name you want here
                         @"label" : self.someLabelView };

// kSomeSpacerConstant is an int or float primitive constant.
// We are wrapping it in @() because this dictionary needs NSNumbers as values.
NSDictionary *metrics = @{ @"spacer" : @(kSomeSpacerConstant) };

[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(spacer)-[logo]-[label]"
                                                                  options:0
                                                                  metrics:metrics
                                                                    views:views]];

If you don’t want to make a new NSDictionary just to hold your metrics or views, just pass in the literal @{ ... } syntax for the metrics: or views: parameters. (But I advise against it for the sake of cleaner code, or if you are building more than one visual format string and you want to reuse the dictionaries.)



来源:https://stackoverflow.com/questions/23680525/layout-how-to-use-property-in-visual-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!