swift4中如何动态创建控件并动态对齐?

How to create controls dynamically and aligned dynamically in swift 4?

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

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

您可以为此使用 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!

}

您可以使用 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
         }

}

希望对您有所帮助 如果没有得到任何积分,请评论