具有自动布局的NSTextFields;打字成长为太空

时间:2014-04-02 18:23:17

标签: cocoa autolayout nsview nstextfield nslayoutconstraint

我想根据这些要求布置我的视图: a)有2个文本字段,最小宽度为90 b)我希望文本字段始终保持10之间的间隙 c)我希望输入的文本字段根据需要变大,然后开始占用右边的空白区域。如果第一个字段是类型,它应该变大并将最后一个字段推入空间(当然只增加第一个字段的宽度) d)我希望文本字段在靠近视图的右边缘后停止增长(标准20像素) e)高度限制很简单:只需22px,顶部与图片顶部对齐

这是我想要的布局:

enter image description here

以下是约束: enter image description here

我已经尝试了一切,但我无法让它发挥作用。我可以在您输入时正确地增加一个文本字段(使用此链接的答案:getting a NSTextField to grow with the text in auto layout?),但无法使其与旁边的第二个文本字段一起使用,推动其占用空的空间。我已经使用了内容拥抱/压缩阻力优先级,给出了文本字段> = 90宽度(右边有一个引脚)......似乎没有在IB中正确设置(使用Xcode 5.1)。如果我添加宽度约束,或者抱怨没有宽度的缺失约束,它会抱怨约束歧义。

任何想法如何让这个工作?

编辑:

这就是我想象的理想布局:约束小于400钉在右边。但它仍然抱怨"不平等约束模糊"那里。

enter image description here

1 个答案:

答案 0 :(得分:1)

自问这个问题差不多一年了,但我认为这是一个值得回答的非常好的问题所以我打算解决你的问题并设法以一种非常简单的方式解决它

您可以点击here在Github中找到示例项目。

请记住,我是使用UIKit做的,所以我希望你在桌面框架中拥有相同的API。

首先我设置这样的约束:

firstTextField: {
    Leading = 20pt (to superView), 
    Width >= 90pt,
    Trailing = 10pt (to secondTextField),
    Vertical Align Y (to superView)
}

secontTextField: {
    Leading = 10pt (to firstTextField), 
    Width >= 90pt,
    Trailing = 20pt (to superView),
    Vertical Align Y (to superView)
}

它用于界面。现在,在代码中,您需要firstTextField的出口以及文本更改时的回调方法。然后,在此方法中,您必须使firstTextField instrinsicContentSize无效:

@interface ViewController () <UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *firstTextField;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.firstTextField addTarget:self
                            action:@selector(textFieldDidChange)
                  forControlEvents:UIControlEventEditingChanged];
}

- (void)textFieldDidChange
{
    [self.firstTextField invalidateIntrinsicContentSize];
}

@end
相关问题