ios - Swift:ScrollView不滚动(如何设置约束)?

标签 ios swift uiscrollview constraints setcontentview

我试图在我的 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)

enter image description here

关于ios - Swift:ScrollView不滚动(如何设置约束)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48305406/

相关文章:

iOS - 搜索栏,错误

ios - 如何将标签文本添加到 DetailDisclosureButton?

ios - 为什么单击按钮时这些框的颜色不会改变? ( swift )

ios - UIscrollView 上的绘图 View 需要无限缩放

ios - 如何在 viewWillAppear 中将 UIScrollView 滚动到底部,当使用自动布局时,没有视觉动画

ios - 以编程方式创建 ViewController+CollectionView 并将其添加到 ScrollView

ios - 如何获取键值并在字典的键中应用条件?

ios - AVAudioRecorder消除低声音

ios - 根据值(360)或百分比(100%)创建彩色圆圈

swift - 是否可以在运行时在 Swift 中动态执行深度属性比较?