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

时间:2018-09-06 11:08:40

标签: ios swift3 uitextfield

我正在使用Swift 4在iOS应用程序上工作。在该项目中,我有一个类似的要求,即必须动态创建控件以及正确的对齐方式。

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

2 个答案:

答案 0 :(得分: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!

}

答案 1 :(得分: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委托中使用标记

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
         }

}

希望它将对您有帮助 如果没有任何评论,请发表评论