問題描述
在 此技術說明中,Apple 聲明您可以通過向 UISCrollView 的超級視圖添加約束來固定/浮動 UIScrollView 的子視圖.我試過了,但我做錯了,我不知道是什么問題.
In this technical Note Apple states that you can make a subview of UIScrollView fixed / floating by adding constraints to UISCrollView's superview. I tried that but I'm doing something wrong and I can't figure out whats the problem.
請注意,您可以通過在視圖和滾動視圖的子樹之外的視圖(例如滾動視圖的超級視圖)之間創建約束,使滾動視圖的子視圖看起來浮動(不滾動)在其他滾動內容之上.
Note that you can make a subview of the scroll view appear to float (not scroll) over the other scrolling content by creating constraints between the view and a view outside the scroll view’s subtree, such as the scroll view’s superview.
這就是我所做的.我已經設置了 UIScrollView 并嘗試將固定視圖添加到滾動視圖的頂部,如下所示:
That's what I did. I have a UIScrollView already set up and try to add the fixed view to the top of the scrollview like the following:
_testOverlay = [[UIView alloc] init];
_testOverlay.backgroundColor = [UIColor blueColor];
_testOverlay.translatesAutoresizingMaskIntoConstraints = NO;
[self.scrollView addSubview:_testOverlay];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[_testOverlay]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_testOverlay)]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_testOverlay(64)]-(>=0)-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_testOverlay)]];
但是,這不起作用,添加的視圖將與滾動視圖一起移動并且不會浮動".有什么想法嗎?
However, this does not work, the added view will move along with the scrollview and does not 'float'. Any ideas whats wrong here?
推薦答案
在視圖和滾動視圖子樹之外的視圖之間,例如滾動視圖的超級視圖.
這部分很關鍵.self.scrollView
是 _testOverlay
的超級視圖.因此,在 @"|[_testOverlay]|"
中,豎線引用 self.scrollView
.你必須用 _testOverlay
和(我想)self.view
之間的約束替換這個約束.我不確定視覺格式語言是否可行,但您當然可以使用 constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant
來實現.它會是這樣的(我不會發布整個代碼,因為它很長):
This part is critical. self.scrollView
is a superview of _testOverlay
. So, in @"|[_testOverlay]|"
vertical bars reference self.scrollView
. You have to replace this constraint with the constraint between _testOverlay
and (I suppose) self.view
. I'm not sure if it's possible with the visual format language, but you certainly can do it with constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant
. It would go like this (I won't post the whole code, because it's looong):
[self.view addConstraint:[NSLayoutConstraint
constraintWithItem:self.view
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:_testOverlay
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:0]];
這篇關于UIScrollView 中的固定/浮動視圖與 AutoLayout的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!