Autolayout UIScrollView约束奇怪的行为

时间:2013-03-26 16:36:17

标签: ios objective-c uiscrollview constraints autolayout

我已经在这里阅读了iOS6发行说明和Autolayout + UIScrollview的一些相关主题,但我有一个奇怪的错误,我不知道如何解决。

视图的层次结构是:

- View
-- UIScrollView
---- UIImageView
---- UILabel

我通过Interface Builder添加了视图中的元素,并使用了Autolayout并保留了默认约束。

我的标签有一个动态文本,其高度是可消耗的(在IB中配置的行数= 0)。 我希望滚动视图自动适应图像视图的高度+标签。

以下是关联视图控制器类的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    self.imageView.translatesAutoresizingMaskIntoConstraints = NO;
    self.label.translatesAutoresizingMaskIntoConstraints = NO;

    self.imageView.image = [UIImage imageNamed:@"image.png"];

    self.label.text = @"Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text Text text END";
    [self.label sizeToFit];

    NSDictionary *viewsDictionnary = NSDictionaryOfVariableBindings(scrollView, imageView, label);
    [self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[imageView]-20-[label]-10-|" options:0 metrics:0 views:viewsDictionnary]];

    self.imageView.userInteractionEnabled = YES;
    [self.imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)]];
}

- (void)tap
{
    [self.navigationController pushViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"View2"] animated:YES];
}

如您所见,我正在为滚动视图添加垂直约束。这看起来效果很好,但我在控制台中有以下消息:

  

2013-03-26 16:24:49.072测试[34704:11303]无法同时进行   满足约束。可能至少有一个限制因素   以下列表是您不想要的。试试这个:(1)看看每一个   约束并试图找出你不期望的东西; (2)找到   添加了不需要的约束或约束并修复它的代码。   (注意:如果您正在看到NSAutoresizingMaskLayoutConstraints,那么   不明白,请参阅UIView属性的文档   translatesAutoresizingMaskIntoConstraints)(       “”       “”)

     

将尝试通过违反约束来恢复   

现在具体的错误: 如果我向下滚动,然后单击图像转到第二个视图,然后单击返回返回当前视图,滚动视图将从先前位置开始,因为它是视图的顶部。而且我无法滚动查看视图。

对不起,我没有足够的声誉来发布图片,但你可以在这里下载示例项目来重现错误:https://docs.google.com/file/d/0B-sCDWMvn-KGS19sUkZnUFdWWTg/edit?usp=sharing

感谢您的帮助, 卢卡斯

EDIT 此处的错误解决方法:UIScrollView wrong offset with Auto Layout

1 个答案:

答案 0 :(得分:1)

根据控制台中的消息。 xib中的垂直约束与您在代码中添加的约束冲突。如果您只想更改imageViewlabel之间的垂直空间,请在xib中进行。

关于你的bug。这是解决方案tap here

相关问题