问题
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.
Enter the value with a "f" postfix like this:
Click Priority. notice how the effective constraint value changes to 0.5:
- 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