Swift iOS以编程方式在导航栏下方设置scrollView约束

所以我的UIViewControllerembedded在导航控制器。 我编程方式添加导航button,现在试图添加此导航栏下面的scrollView。 我遇到的问题是填充完整的框架大小,并在导航栏下。

我如何编程设置此滚动视图的约束?

var scrollView: UIScrollView! var containerView = UIView() override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Filters" // add some buttons on the navigation self.scrollView = UIScrollView() self.scrollView.backgroundColor = UIColor.grayColor() self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height) containerView = UIView() scrollView.addSubview(containerView) view.addSubview(scrollView) let label = UILabel(frame: CGRectMake(0, 0, 100, 21)) label.text = "my label" containerView.addSubview(label) } 

虽然Clafou的答案当然是正确的,但如果您不需要透明度并且想要在导航栏下开始,那么真正正确的方法就是更改ViewController的行为,使其适合内容。 要做到这一点,你有两个select:

1)假设你有Storyboard,进入ViewController Attributes Inspector并禁用“Under top bars”

在这里输入图像说明

2)假设你是通过代码的一切,你会想要寻找以下属性 – edgesForExtendedLayoutextendedLayoutIncludesOpaqueBars 。 已经有很好的答案了,所以我不会在这里介绍。

希望能帮助到你!

使用你的UIScrollViewcontentInset属性。 例如,如果你想在顶部的44点差距:

 self.scrollView.contentInset = UIEdgeInsets(top: 44, left: 0, bottom: 0, right: 0) 

在使用auto-layout ,只要确保你给Top Layout GuideUIScrollViewtop-constraint ,而不是滚动视图的top-constraint视图。

在Objective-C中,我通常将'edgesForExtendedLayout'属性设置为UIRectEdgeNone

 if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) self.edgesForExtendedLayout = UIRectEdgeNone; 

不过,我会build议将约束绑定到topLayoutGuide

 func addScrollViewConstraints() { var scrollViewContraints = [NSLayoutConstraint]() scrollViewContraints.append(NSLayoutConstraint(item: scrollView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.topLayoutGuide, attribute:NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0)) scrollViewContraints.append(NSLayoutConstraint(item: scrollView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.bottomLayoutGuide, attribute:NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0)) scrollViewContraints.append(NSLayoutConstraint(item: scrollView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute:NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0.0)) scrollViewContraints.append(NSLayoutConstraint(item: scrollView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute:NSLayoutAttribute.Trailing, multiplier: 1.0, constant: 0.0)) self.view.addConstraints(scrollViewContraints) } 

希望这对你有用。

我设法在iOS11上运行的唯一方法就是这样

 if (@available(iOS 11.0, *)) { scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever; } else { // Fallback on earlier versions }