![](/img/trans.png)
[英]Is it possible to create textfield , buttons dynamically from the json response swift ios?
[英]Swift :How to create dynamic layout from json response iOS
我想根据从服务器获取的 json 响应创建动态布局。 我对使用带有约束的视图或使用 tableview 来实现此布局的方法感到困惑。 我研究了另一种方法是制作不同类型的 xib 视图,在解析响应后,检查每个元素类型并在 tableview 单元格中调用相应的视图。 我只是想要一个建议,我怎样才能以更好的方式创建这个布局。
json 响应是:
"data": {
"elementperrowtwo": {
[
{
“fieldid”: “1”,
“fieldtype”: “label”,
“fieldtext”: “OrderDate”,
“fieldcontrolno”: ”1”,
“displaycolumntype”: “2”
},
{
“fieldid”: “2”,
“fieldtype”: “textfield”,
“fieldtext”: “”,
“fieldcontrolno”: ”2”,
“displaycolumntype”: “2”
},
{
“fieldid”: “3”,
“fieldtype”: “label”,
“fieldtext”: “OurReference”,
“fieldcontrolno”: ”1”,
“displaycolumntype”: “2”
},
{
“fieldid”: “4”,
“fieldtype”: “textfield”,
“fieldtext”: “”,
“fieldcontrolno”: ”2”,
“displaycolumntype”: “2”
}
],
"elementperrowone": [
{
“fieldid”: “8”,
“fieldtype”: “label”,
“fieldtext”: “Buyer”,
“fieldcontrolno”: ”1”,
“displaycolumntype”: “1”
},
{
“fieldid”: “9”,
“fieldtype”: “textfield”,
“fieldtext”: “”,
“fieldcontrolno”: ”2”,
“displaycolumntype”: “1”
},
{
“fieldid”: “16”,
“fieldtype”: “dropdown”,
“fieldarray”: [
{
“id”: “1”,
“name”: “australia”
},
{
“id”: “2”,
“name”: “china”
},
{
“id”: “3”,
“name”: “India”
}
],
“fieldcontrolno”: ”3”,
“displaycolumntype”: “1”
}
]
}
实现动态布局的最佳方法是使用堆栈视图。 使用 xib 您可以初始化视图并将其添加为堆栈视图内的排列子视图。
首先,您需要创建一个扩展函数,以便您可以重用它。
extension UIView {
func loadFromNib() {
Bundle.main.loadNibNamed(String(describing: type(of: self)), owner: self, options: nil)
}
}
设计完 xib 后,您只需要从 xib 初始化视图即可使用它。 Bellow 是用于从 xib 初始化视图的代码。
class FormLabelFieldCell: UIView {
@IBOutlet weak var contentView: UIView!
@IBOutlet weak var lblTitle: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() {
loadFromNib()
addSubview(contentView)
contentView.frame = self.bounds
contentView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
}
}
您可以将其添加为子视图
let cell = FormLabelFieldCell()
mainStack.addArrangedSubview(cell.contentView)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.