【发布时间】:2018-10-07 23:47:21
【问题描述】:
所以,我创建了一个VerticalView 来处理在scrollview 中添加多个视图,它还处理scrollview 内容大小。它的定义是这样的:
import UIKit
class VerticalLayout: UIView {
var yOffsets: [CGFloat] = []
var heightValue : CGFloat = 0.0
init(width: CGFloat) {
super.init(frame: CGRect(x:0, y:0, width:width, height:0))
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
var height: CGFloat = 0
for i in 0..<subviews.count {
let view = subviews[i] as UIView
view.layoutSubviews()
height += yOffsets[i]
view.frame.origin.y = height
height += view.frame.height
}
self.frame.size.height = height
self.heightValue = height
self.frame.size.height = height
self.heightValue = height
let ff = self.superview
let dd = ff?.superview as! UIScrollView
dd.contentSize = CGSize.init(width: self.frame.size.width, height: height)
}
override func addSubview(_ view: UIView) {
yOffsets.append(view.frame.origin.y)
super.addSubview(view)
}
func removeAll() {
for view in subviews {
view.removeFromSuperview()
}
yOffsets.removeAll(keepingCapacity: false)
}
}
我的View Controller 看起来像这样:
import UIKit
import os.log
class ViewController: UIViewController {
@IBOutlet var contentview: UIView!
@IBOutlet var scrollview: UIScrollView!
let colors = [UIColor.red,UIColor.green,UIColor.blue,UIColor.magenta,UIColor.yellow]
override func viewDidLoad() {
super.viewDidLoad()
contentview.backgroundColor = UIColor.lightGray
let vLayout = VerticalLayout(width: view.frame.width)
vLayout.backgroundColor = UIColor.cyan
contentview.addSubview(vLayout)
for i in 0..<14
{
vLayout.addSubview(getView(vLayout.frame.width,color: colors[i % colors.count]))
}
}
func getView(_ width: CGFloat,color:UIColor) -> UIView
{
let view = UITextField(frame: CGRect(x:0, y:0, width:width, height:100))
view.backgroundColor = color
view.placeholder = "Write here"
return view
}
}
这是视图控制器视图:
constrains 对应于 contentview 是:
我的UITextField 最多只能点击 10-12 个文本字段,具体取决于设备大小。我错过了什么?
【问题讨论】:
标签: ios swift uiscrollview uitextfield