【问题标题】:Swift, XCode 6, add new section to existing uitableviewSwift,XCode 6,将新部分添加到现有的 uitableview
【发布时间】:2015-11-25 05:23:57
【问题描述】:

我有一个视图,其中顶部有一个按钮,下方有一个表格视图。我默认显示一个部分。我想要实现的是,当单击按钮时,我想在默认部分的正下方添加一个全新的部分。当按下按钮时,我想继续在现有部分下方附加新部分。

点击按钮之前:

按钮

 <UITableView>
     Default Section Header
       Row 1
       Row 2
       Row 3
</UITableView>

按下按钮后

按钮

<UITableView>
  Default Section Header
   Row 1
   Row 2
   Row 3

  Newly added section header
   Row 1
   Row 2
   Row 3
   Row 4
</UITableView>

我搜索了很多,但只找到了 Objective-C 参考资料。

我知道我需要使用以下功能:

insertRowsAtIndexPathsinsertSections

但我真的不明白如何在 Swift 中使用它。我是 iOS 开发新手。

请帮助我。提前致谢!

【问题讨论】:

  • 您能否根据您的尝试评论您的代码。上传一张你想要输出的图片,如果有的话?

标签: ios xcode swift uitableview xcode6


【解决方案1】:

我只是给你一些代码。用作参考。

class MyInfoView: UIView, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var myInfoTableView: UITableView!

var headerNamesArray: [String]?//= ["Personal Details", "Contact Details","Emergency Contacts", "Dependents", "Immigration", "Job", "Salary", "Report-to", "Qualifications", "Memberships"]
var cellDetailsArray:NSDictionary?
var currentExpandedIndex:Int = -1
var isButtonTapped:Bool = false

//MARK:- Register Tableview Method -
func registerTableView()
{
    println(self.frame)
    myInfoTableView.frame = CGRectMake(0.0, 0.0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame) - 64)
    myInfoTableView.registerNib(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "InfoCellID")
    loadTableViewDetails()
}
//MARK:- Loading details from Plist -
func loadTableViewDetails()
{
    cellDetailsArray = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("TextFieldNames", ofType: "plist")!)
    headerNamesArray = cellDetailsArray!.allKeys as? [String]
    println(cellDetailsArray)
}
//MARK:- tableview header button Action -
func headerButtonTapped(sender: AnyObject)
{
    isButtonTapped = !isButtonTapped

    var anIndex:NSInteger = sender.tag
    var indexSet:NSMutableIndexSet = NSMutableIndexSet(index: anIndex)

    if anIndex == currentExpandedIndex {
        //            myInfoTableView.deleteRowsAtIndexPaths( (currentExpandedIndex, withRowAnimation: UITableViewRowAnimation.Right);
        currentExpandedIndex = -1
    } else if (currentExpandedIndex != -1 ) {
        indexSet.addIndex(currentExpandedIndex)
        currentExpandedIndex =  anIndex
        isButtonTapped = true
    } else {
        currentExpandedIndex = anIndex
    }
    println(indexSet)
    myInfoTableView.reloadSections(indexSet ,withRowAnimation:UITableViewRowAnimation.Middle)
}
}
  //MARK:- TableView Delegate and DataSource Methods -
 extension MyInfoView: UITableViewDataSource, UITableViewDelegate {

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return headerNamesArray!.count
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    cellDetailsArray![headerNamesArray![section]];
    return cellDetailsArray![headerNamesArray![section]]!.count;
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("InfoCellID", forIndexPath: indexPath) as! CustomTableViewCell
    var headerSection = indexPath.section
    cell.userTextField.placeholder = cellDetailsArray![headerNamesArray![headerSection]]![indexPath.row] as? String

    return cell
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if isButtonTapped && currentExpandedIndex == indexPath.section {
        return 40.0
    }
    else {
        return 0.0
    }
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 0.5
}

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = NSBundle.mainBundle().loadNibNamed("TableHeaderView", owner: self, options: nil) [0] as! TableHeaderView
    headerView.headerButton.setTitle(headerNamesArray![section], forState: .Normal)
    headerView.applyViewStyle()
    headerView.headerButton.tag = section
    headerView.headerButton.addTarget(self, action: Selector("headerButtonTapped:"), forControlEvents:.TouchUpInside)
    headerView.arrowImageView.image = UIImage(named: "sidearrow.png")
    if currentExpandedIndex == section {
        headerView.arrowImageView.image = UIImage(named: "downarrow.png")
    }
    return headerView
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 40.0
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

}
}

【讨论】:

    【解决方案2】:

    不,您不需要插入任何内容。只需更新要显示的数据的变量并重新加载 tableview。

    例如在 Swift 3

    class TableViewController: UITableViewController {
    
    var sections = ["pizza", "deep dish pizza"]
    
    var items = [["Margarita", "BBQ Chicken", "Pepperoni"], ["sausage", "meat lovers", "veggie lovers"]]
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sections[section]
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items[section].count
    }
    

    然后你可以这样做来更新tableview:

    fun onClick(){
        sections.append("calzone")
        items[2].append(["sausage", "chicken pesto", "prawns", "mushrooms"])
        tableview.reloadData()
    }
    

    免责声明:如果您在 Xcode 6 上,您可能正在使用 Swift 2.2,但功能显然相似,并且前提保持不变。

    【讨论】:

    • 重新加载整个表格视图是不好的做法。
    • @bibscy 请随时提交您认为更恰当地回答这个问题的解决方案,但是自从我回答这个问题已经 2 年了,我仍然坚持这个代码、方法和实践。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 2016-06-19
    相关资源
    最近更新 更多