Can you enter a constraint value with decimal in IB?

无人久伴 提交于 2019-12-05 15:57:32

问题


Here is to hoping it is a simple setting.

I cannot enter a constraint value with decimals in IB. Whenever I enter a value with decimals and press enter, the system rounds it!

I don't have this problem when creating constraints in code. Only in IB.

Is there a way?


回答1:


Yes, you can.

  1. Enter the value with a "f" postfix like this:

  2. Click Priority. notice how the effective constraint value changes to 0.5:

  3. Hit ESC



回答2:


It has to be done programmatically, I believe. As of Xcode 6.3, constraint constant values seem to be restricted to integers in the storyboard editor (unlike multiplier values, which can be decimals).

For Googlers, here's how to do it:

To specify a decimal value for a constraint defined in a storyboard, you can set the constant property of a constraint iVar. Here's an example of setting a height constraint to 0.5f:

In your header:

@property (nonatomic, retain) IBOutlet NSLayoutConstraint *separatorHeightConstraint;

then connect the IBOutlet to the constraint in the storyboard.

In your implementation:

-(void)layoutSubviews {
    [super layoutSubviews];
    self.separatorHeightConstraint.constant = 0.5f;
}

That's all!




回答3:


If you need to set constant decimal value in storyboard that is not dependent on screen scale, you can use user defined runtime attributes, for example for constraint constant it would be:

Key Path: constant Type: Number Value: 0,5


If you want to make a delimiter by making a view with 1-pixel width on @2x and @3x devices you can use a constraint that sets view's width/height and set its class to your own constraint subclass. Example of such subclass: OnePixelWidthConstraint.h:

#import <UIKit/UIKit.h>

@interface OnePixelWidthConstraint : NSLayoutConstraint
@end

OnePixelWidthConstraint.m:

#import "OnePixelWidthConstraint.h"

@implementation OnePixelWidthConstraint

- (CGFloat)constant {
    return 1./[UIScreen mainScreen].scale;
}

@end

To calculate the value only once:

- (CGFloat)constant {
    static CGFloat onePixel = 0;
    return onePixel?:(onePixel = 1./[UIScreen mainScreen].scale);
}



回答4:


I would do that in :

- (void)updateConstraints {
   self.separatorHeightConstraint.constant = 0.5f;
   [super updateConstraints];
}



回答5:


Type the desired decimal value with a leading 0.

e.g. 0.9, not .9



来源:https://stackoverflow.com/questions/27500448/can-you-enter-a-constraint-value-with-decimal-in-ib

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