我试图在我的 Storyboard中设置一个具有自动布局的 ScrollView ,并用代码中的几个按钮填充它,但是 ScrollView 不会滚动,而且我不明白如何设置约束使滚动可用?
特别是如何设置内容 View 的约束(那是什么?)。
在 Storyboard 中, ScrollView 放置在屏幕底部(距安全区域 20 像素),从前导到尾随。它的尺寸为 375x80。
现在在代码中,这是 ScrollView 如何用按钮填充以及如何设置的:
override func viewDidLoad() {
super.viewDidLoad()
var xCoord: CGFloat = 5
var yCoord: CGFloat = 5
let buttonWidth: CGFloat = 70
let buttonHeight: CGFloat = 70
let gapBetweenButtons: CGFloat = 5
var itemCount = 0
for i in 0..<CIFilterNames.count {
itemCount = 1
// Button properties
let filterButton = UIButton(type: .custom)
filterButton.frame = CGRect(x: xCoord, y: yCoord, width: buttonWidth, height: buttonHeight)
filterButton.tag = itemCount
filterButton.addTarget(self, action: #selector(ViewController.filterButtonTapped(sender:)), for: .touchUpInside)
filterButton.layer.cornerRadius = 6
filterButton.clipsToBounds = true
//Code for filters will be added here
let ciContext = CIContext(options: nil)
let coreImage = CIImage(image: originalImage.image!)
let filter = CIFilter(name: "\(CIFilterNames[i])")
filter!.setDefaults()
filter?.setValue(coreImage, forKey: kCIInputImageKey)
let filteredImageDate = filter!.value(forKey: kCIOutputImageKey) as! CIImage
let filteredImageRef = ciContext.createCGImage(filteredImageDate, from: filteredImageDate.extent)
let imageForButton = UIImage(cgImage: filteredImageRef!)
// Asign filtered image to the button
filterButton.setBackgroundImage(imageForButton, for: .normal)
// Add buttons in the scrollView
xCoord += buttonWidth + gapBetweenButtons
filterScrollView.addSubview(filterButton)
}
filterScrollView.contentSize = CGSize(width: buttonWidth * CGFloat(itemCount + 2), height: yCoord)
filterScrollView.isScrollEnabled = true
}
根据设备尺寸,会显示 4 或 5 个按钮,但不会更多,并且无法滚动。
如何才能实现滚动?
最佳答案
原因在于 itemCount ,您将其设置为 itemCount + 2 将是 3,因为 for 循环中 itemCount 为 1,因此将其设置为等于数组大小
filterScrollView.contentSize = CGSize(width: buttonWidth * CIFilterNames.count , height: yCoord)
关于ios - Swift:ScrollView不滚动(如何设置约束)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48305406/