gpt4 book ai didi

ios - 无法使用纯自动布局约束创建 UIScrollerView

转载 作者:行者123 更新时间:2023-11-30 13:29:53 25 4
gpt4 key购买 nike

我精简了代码,以便于理解。

假设您有一个 Controller ,并且想要使用纯自动布局添加一个简单的滚动条。

您可以按如下方式调用我的函数工具(如下提供):

// Create scroll view
let strip = addStripCategoryTo(view)

// Attach it to the view, vertically and horizontally
strip.topAnchor.constraintEqualToAnchor(view.topAnchor).active = true
strip.leftAnchor.constraintEqualToAnchor(view.leftAnchor).active = true


// The function
func addStripCategoryTo(parent: UIView) -> UIView {

let h:CGFloat = 128
let w = 2*h/3
let n = 5
let width = w * CGFloat(n)
let height = h

// Scroll view
let scrollview = UIScrollView()
parent.addSubview(scrollview)

scrollview.scrollEnabled = true
scrollview.translatesAutoresizingMaskIntoConstraints = false
scrollview.widthAnchor .constraintEqualToAnchor(parent.widthAnchor).active = true
scrollview.heightAnchor.constraintEqualToConstant(h).active = true

scrollview.layer.borderWidth = 2
scrollview.layer.borderColor = UIColor.greenColor().CGColor
scrollview.backgroundColor = UIColor.brownColor()

// Scroll view content
let contentView = UIView() //frame:CGRect(origin: CGPointZero, size:CGSize(width: width, height: height)))
scrollview.addSubview(contentView)
contentView.backgroundColor = UIColor.redColor()
contentView.layer.borderWidth = 10
contentView.layer.borderColor = UIColor.blueColor().CGColor
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.centerYAnchor.constraintEqualToAnchor(scrollview.centerYAnchor).active = true
contentView.widthAnchor .constraintEqualToConstant(width).active = true
contentView.heightAnchor.constraintEqualToConstant(height).active = true

return scrollview
}

不幸的是,我无法水平滚动,请参见截图:

enter image description here

我错过了什么?

最佳答案

你的约束应该是这样的,

ScrollView - 顶部、底部、前导、尾随

ContentView - 顶部、底部、前导、尾随、固定宽度、在容器中垂直居中(中心 y)

并且您的内容 View 的宽度应该大于屏幕宽度,那么您也可以水平滚动希望这会有所帮助:)

关于ios - 无法使用纯自动布局约束创建 UIScrollerView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36692019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com