我需要动态创建带有多个视图的堆栈视图,因为视图数量仅在运行时才知道。
每个视图都包含一个UITextField
class AccountParameterView: UIView {
public var inputField = UITextField()
private struct InputFieldParam {
static let x: CGFloat = 0
static let y: CGFloat = 50
static let height: CGFloat = 20
}
override init(frame: CGRect){
super.init(frame: frame)
}
convenience init(frame: CGRect, with field: Field){
self.init(frame: frame)
self.field = field
loadElements()
}
required init?(coder aDecoder: NSCoder){
super.init(coder: aDecoder)
loadElements()
}
// Programmatically put the different element in the view
func loadElements() {
// shows the input field
inputField.frame = CGRect(x: InputFieldParam.x,
y: InputFieldParam.y,
width: frame.width,
height: InputFieldParam.height)
}
在我的视图控制器中,我创建了一个stackView并添加了几个AccountParameterView
:
func addStackView(){
for field in MyList!.fields{
if field.type != FieldType.list{
// position of the views
let viewFrame = CGRect(x: ViewConst.x,
y: view.frame.height - ViewConst.vertOffset,
width: view.frame.width,
height: ViewConst.height)
let myView = AccountParameterView(frame: viewFrame, with: field)
ParamViews.append(myView)
}
}
let stackView = getStackView()
for view in ParamViews {
stackView.addArrangedSubview(view)
}
self.view.addSubview(stackView)
}
我在viewDidLoad
中调用此函数。一切都正确显示在屏幕上,但是无法将焦点放在任何UITextField
上。
我试图使视图控制器成为每个UITextField
的委托,但没有任何变化,UITextField
仍然无法访问