如何动态创建控件并在swift 4中动态对齐?

问题描述 投票:0回答:2

我正在使用Swift 4开发iOS应用程序。在该项目中我有要求,我必须动态创建控件以及正确的对齐方式。

例如,当我点击该按钮时,我有一个按钮,我正在接受服务,因为我正在获取包含4个对象的json数据。基于此我必须动态创建控件,动态对齐也应该这样做。我尝试了很多例子和教程。我没有找到任何解决方案。

ios swift3 uitextfield
2个回答
7
投票

enter image description here

您可以使用UITableView,这是示例:

import UIKit

class ViewController: UIViewController {
@IBOutlet weak var tableview: UITableView!
var nameArr :[String] = []
override func viewDidLoad() {
    super.viewDidLoad()
    tableview.delegate  =  self
    tableview.dataSource = self
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
@IBAction func four_btn(_ sender: Any) {
    nameArr.removeAll()
    let nameData = ["First Name","Middle Name","Last Name","DOB"]
    nameArr += nameData
    tableview.reloadData()
}

@IBAction func eight_btn(_ sender: Any) {
    nameArr.removeAll()
    let nameData = ["Salutation","First Name","Middle Name","Last Name","DOB","Gender","Mobile","Email"]
    nameArr += nameData
    tableview.reloadData()
}

}
extension ViewController: UITableViewDataSource, UITableViewDelegate {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return nameArr.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! tableviewCells
    cell.nameLabel.text = nameArr[indexPath.row]
    return cell
}


}
class tableviewCells : UITableViewCell{
@IBOutlet weak var nameLabel: UILabel!

}

0
投票

你可以使用UITableView你的场景是这样的,一个用户可能有5个记录而另一个可能有10或12个记录意味着你要动态工作

如果有2个按钮调用2个不同的API,那么就像这样管理2个不同的数组

var arr1 = NSArray()
var arr2 = NSArray()
var isAPI1Called = Bool()

保存不同数组中两个api的响应

然后只需在按钮水龙头上管理标志,并在这样的合适视图中

@IBAction func btn1(_ sender: Any) {
 isAPI1Called = true
self.API1Called()
}

@IBAction func btn2(_ sender: Any) {
isAPI1Called = false
self.API1Called()
}

现在在UITableview Delegate中使用这样的标志

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if isAPI1Called
    {
    return arr1.count
    }
    else
    { 
     return arr2.count
    }

}

如果UI更改,请根据您的要求加载UITableviewCell

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         if isAPI1Called
         {
          let cell = tableView.dequeueReusableCell(withIdentifier: "Cell1", for: indexPath) as! UITableviewCell
         //Do your required stuff here
         return cell
         }
         else
         {
          let cell = tableView.dequeueReusableCell(withIdentifier: "Cell1", for: indexPath) as! UITableviewCell
         //Do your required stuff here
         return cell
         }

}

希望它会帮助你评论如果没有得到任何意义

© www.soinside.com 2019 - 2024. All rights reserved.