ios - 使用 constraintsWithVisualFormat 的自动布局效果不佳

标签 ios swift ios-autolayout

我已设置 ScrollView 并向 ScrollView 添加约束。但它显示空白屏幕。请检查以下代码。

override func loadView()
    {
        super.loadView()
        scrollView = UIScrollView(frame:CGRectZero)
        scrollView.backgroundColor = UIColor.whiteColor()

        scrollView.sizeToFit()

        self.view.addSubview(scrollView)
        scrollView.backgroundColor = UIColor.blueColor()

        contentView = UIView()
//        contentView.setTranslatesAutoresizingMaskIntoConstraints(false)
        contentView.backgroundColor = UIColor.redColor()
        scrollView.addSubview(contentView)

        var viewBindingsDictBoth = [String: AnyObject]()
        viewBindingsDictBoth["scrollView"] = scrollView
        viewBindingsDictBoth["contentView"] = contentView
        viewBindingsDictBoth["mainView"] = self.view


        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[scrollView]-0-|",options: [], metrics: nil,  views:viewBindingsDictBoth))

        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[scrollView]-0-|",options: [], metrics: nil, views:viewBindingsDictBoth))

        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[contentView]|",options: [], metrics: nil, views:viewBindingsDictBoth))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[contentView]|",options: [], metrics: nil, views:viewBindingsDictBoth))

        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[contentView(==mainView)]",options: [], metrics: nil, views:viewBindingsDictBoth))

        self.view.contentMode = UIViewContentMode.Redraw
    }

提前致谢..

最佳答案

你最想念的是

scrollView.translatesAutoresizingMaskIntoConstraints = false

contentView.translatesAutoresizingMaskIntoConstraints = false

我认为您的某些约束并不完美,但最大的问题是每个 View 都默认使用其自动调整属性进行定位。这些将与您的约束发生冲突。

来自 UIView.translatesAutoresizingMaskIntoConstraints documentation :

Note that the autoresizing mask constraints fully specify the view’s size and position; therefore, you cannot add additional constraints to modify this size or position without introducing conflicts. If you want to use Auto Layout to dynamically calculate the size and position of your view, you must set this property to false, and then provide a non ambiguous, nonconflicting set of constraints for the view.

(强调我的)

关于ios - 使用 constraintsWithVisualFormat 的自动布局效果不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37570705/

相关文章:

iphone - IOS Core蓝牙外设连接请求

xcode - 如何在同一 View Controller 上的 2 个不同 View 上实现随机生成器?

ios - 根据选择显示所有选定值的动态高度 MultipleSelectorRow

ios - 当约束到包含多行 UILabel 的 UIStackview 时,UITableViewCell 高度不是动态的

ios - 为什么我的 UILabel 的 AutoLayout 不起作用

ios - 使用 equalToSystemSpacingAfter 前后边距的布局

ios - 从字节中获取位的值 | swift 5

ios - 如何强制 VoiceOver 不读取 View Controller 标题的 "heading"字

ios - 使用 TeamCity 代码设计的 Xcode 8 FaSTLane 构建失败,退出代码为 1

ios - 在 swift 中使用 bridgeToObjectiveC()