【问题标题】:UIScrollView does not scroll in customViewUIScrollView 在 customView 中不滚动
【发布时间】:2018-09-14 07:48:52
【问题描述】:

我正在制作一个自定义视图,它包含一个UIScrollView。但是这个滚动视图不滚动。

视图层次结构如下:

- mainView
    - UIScrollView
        - contentView

A picture for illustration purposes

这是我的自定义视图代码:

class MyCustomView: UIView {

    @IBOutlet var mainView: UIView!
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var scrollViewContetnView: UIView!

    // MARK: - Methods

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.customInit()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.customInit()
    }

    // MARK: Custom

    func customInit() {
        Bundle.main.loadNibNamed("EmoKeyboard", owner: self, options: nil)
        self.addSubview(mainView)
        self.mainView.frame = self.bounds
        self.mainView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    }

    func makeTabItem(count: Int) {
        for i in 0...count {
            let icon = UIButton()
            icon.frame.size = CGSize(width: 28, height: 28)
            icon.center.y = self.scrollViewContentView.center.y
            icon.frame.origin.x = 10 + (CGFloat(i) * 28) + (CGFloat(i) * 10)
            icon.backgroundColor = UIColor.black

            self.scrollViewContentView.addSubview(icon)
        }
    }

}

我做错了什么?

【问题讨论】:

  • 这很难说,我只看过故事板做这种事情,这需要内容视图被限制在滚动视图的所有边缘,你想要增长的边缘有较低的优先级。
  • scrollViewContentView 需要更新 frame,scrollView 需要 contentsize。
  • 您是否检查过 mainView 和 scrollView 上的 isUserInteractionEnabled 属性?

标签: ios swift uiscrollview uikit


【解决方案1】:

您必须根据按钮数量或为每个按钮添加约束手动设置scrollView 中的contentSize。 另一种可能的(!)更简单的方法是将UIStackView 添加为scrollView 的子视图,并为每个按钮添加高度/宽度约束。

【讨论】:

    【解决方案2】:

    添加contentSize:

    scrollView.contentSize = CGSize(width: 0, height: 900) //You can use self view size height to set height means replace 900 according to your requirment 
    

    【讨论】:

      【解决方案3】:

      每次将UIButton 添加到scrollViewContentView 时,都应该更新scrollViewContentView 的宽度,因为它的宽度应该等于您添加到其中的所有UIButton items 的宽度加上项目之间的间距总和。

      【讨论】:

        【解决方案4】:
        1. 计算内容矩形 ViewController ~> viewDidLayoutSubviews

          var contentRect = CGRect.zero

          在 contentView.subviews 中查看 { contentRect = contentRect.union(view.frame) }

          contentRect = contentRect.union(填充)

        2. 应用矩形

          scrollView.contentSize = contentRect.size

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-24
          • 1970-01-01
          • 1970-01-01
          • 2013-11-15
          • 2013-07-02
          相关资源
          最近更新 更多