UIScrollView
需要它的內容的大小,從它的子視圖,所以它只會是因爲它所包含的內容一樣大。我們無法獨立設置它的大小。一切都應該在子視圖中。
上的myScrollView
大小決定你想:
let myViewWidth = myView.frame.width
let myViewHeight = myView.frame.height
let screenWidth = myScrollView.frame.width
let scrollContentWidth = myViewWidth + screenWidth
創建一個子視圖,我們稱之爲widthView
let widthView = UIView(frame: CGFloat(x: 0, y: 0, width: scrollContentWidth, height: myViewHeight))
myScrollView.addSubview(widthView)
let leadingEdgeConstraint = NSLayoutConstraint(item: widthView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: myScrollView, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)
myScrollView.addConstraint(leadingEdgeConstraint)
let trailingEdgeConstraint = NSLayoutConstraint(item: widthView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: myScrollView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0)
myScrollView.addConstraint(trailingEdgeConstraint)
let widthContainerConstraint = NSLayoutConstraint(item: widthView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: scrollContentWidth)
myScrollView.addConstraint(widthContainerConstraint)
現在您的MyView的加入到這一觀點:
widthView.addSubview(myView)
myView.translatesAutoresizingMaskIntoConstraints = false
let horizontalConstraint = NSLayoutConstraint(item: myView , attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: widthView , attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0)
widthView.addConstraint(horizontalConstraint)
let heightConstraint = NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: myViewHeight)
widthView.addConstraint(heightConstraint)
let widthConstraint = NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: myViewWidth)
widthView.addConstraint(widthConstraint)
當你說「底」的的UIScrollView的,你的意思是滾動到頁面底部時,它的出現,或者停留在屏幕浮動在滾動視圖?我假設前者。所以'myView'應該是'myScrollView'的子視圖。此外,您目前的垂直限制被固定在頂部,而不是底部。 – Tim
Hi @Tim,當然UIView是UIScrollview的子視圖;我想要的是當用戶啓動應用程序時,它會在滾動視圖的末尾顯示uiview,這對我來說意味着用戶可以向左滾動但不向右滾動(不管他有多少/她可以滾動到左側) – Jibeee
明白了,沒有意識到你在水平滾動。你的'scrollView'還有什麼?你說它沒有出現,我的猜測是被掩蓋了。無論視圖是其餘的scrollView內容,都需要被限制在'myView'的左邊緣。 – Tim