【发布时间】:2018-04-10 15:45:53
【问题描述】:
我试图在UITableView Cell 中创建一个动态生成的UIScrollView。 UIScrollView 是在 ScrollViewClass 中使用 build function 构建的。该类采用一组视图并将它们并排放置,然后返回一个ScrollView,然后可以将其添加到cell's subviews。 ScrollView 已添加且可见,但是 ScrollView 不会按预期水平滚动。所有的代码都可以在下面找到。
ScrollViewClass
import Foundation
import UIKit
class ScrollViewClass {
let ArrayOfViews: [UIView]
let scrollView = UIScrollView()
init(ArrayOfViews: [UIView]) {
self.ArrayOfViews = ArrayOfViews
}
func build() -> UIScrollView {
scrollView.isScrollEnabled = true
scrollView.frame.size.width = UIScreen.main.bounds.width
scrollView.frame.size.height = UIScreen.main.bounds.height
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.isPagingEnabled = true
scrollView.contentSize = CGSize(width: 2000, height: 500)
scrollView.showsHorizontalScrollIndicator = true
for (index, views) in ArrayOfViews.enumerated() {
scrollView.addSubview(views)
views.frame.origin.x = CGFloat(index) * UIScreen.main.bounds.width / 2
print(index)
}
return scrollView
}
}
TableView CellForRowAt
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: "CellID")
cell.selectionStyle = UITableViewCellSelectionStyle.none;
let view1 = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 500))
let view2 = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 500))
let view3 = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 500))
view1.backgroundColor = UIColor.blue
view2.backgroundColor = UIColor.green
view3.backgroundColor = UIColor.red
let ArrayOfViews = [view1, view2, view3]
let scrollView = ScrollViewClass(ArrayOfViews: ArrayOfViews)
cell.addSubview(scrollView.build())
return cell
}
【问题讨论】:
-
你正在设置
scrollView.translatesAutoresizingMaskIntoConstraints = false,但你没有给它任何限制。试试scrollView.backgroundColor = .red,我猜你不会看到任何红色 - 但你可以看到它的子视图,因为.clipsToBounds没有设置为true。 -
@DonMag 我会解决这个问题的!但是,这仍然不能解决滚动问题
-
附带说明,如果您每次调用
cellForRowAt时都添加一个滚动视图,您将多次添加它(重复使用单元格)。 -
您是否检查过它是否解决了滚动问题?
-
@DonMag 抱歉,我该怎么做呢,我对 xcode 还很陌生。但这确实是有道理的,好像视图只是由于剪辑而被禁用,然后触摸检测不存在
标签: ios swift uitableview uiscrollview