在tableView的顶部添加一行

时间:2016-07-10 09:08:48

标签: ios uitableview swift2 xcode7

我想在top let indexPath : [NSIndexPath] = [NSIndexPath(forRow: 0, inSection: 0)]的tableView中添加一行 parentTableView.insertRowsAtIndexPaths(indexPath, withRowAnimation: .Fade)但是它将它添加到tableView的底部

这是我的代码: -

import UIKit

class ViewController: UIViewController , UITableViewDelegate, UITableViewDataSource,transferDelegate , UIViewControllerTransitioningDelegate{

var xibName : String = "HomepageFeedCellHeader"


var lords : [String] = ["name1","name2","name3"]

var queens : [String] = ["--","q1","q2"]

var desc : [String] = ["alpha","beta","gamma"]

var  menProfilePictures : [UIImage] = [UIImage(named: "DaarioNaharis")!,UIImage(named: "JaimeLannister")!,UIImage(named: "LordVarys")!]

@IBOutlet weak var postButton: UIButton!

@IBOutlet weak var parentTableView: UITableView!

@IBOutlet weak var pickImages: UIButton!

var a : ParentTableViewCell = ParentTableViewCell()

@IBOutlet weak var postTextView: UITextView!





override func viewDidLoad() {

    super.viewDidLoad()



    parentTableView.delegate = self
    parentTableView.dataSource = self


}




func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}




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



func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = parentTableView.dequeueReusableCellWithIdentifier("ParentCell", forIndexPath: indexPath) as! ParentTableViewCell


    cell.transferingDelegate = self


    cell.feedPostUsername.text = lords[indexPath.row]
    cell.feedPostUserDetails.text = queens[indexPath.row]
    cell.feedPostDescription.text = desc[indexPath.row]
    cell.feedUserProfilePictures.image = menProfilePictures[indexPath.row]
    cell.selectionStyle = .None


    return cell


}

func transfer(itemNo : Int) {

    print("call recieved in viewController from item \(itemNo)")

    let imagePopOverScene = self.navigationController?.storyboard?.instantiateViewControllerWithIdentifier("ImagePopOverViewControllerVC_ID") as? ImagePopOverViewController

    print("itemNo in viewControlle \(itemNo)")
    if itemNo < 3{

        imagePopOverScene?.setImage = menProfilePictures[itemNo]

    }else{

        imagePopOverScene?.setImage = UIImage(named: "defaultProfilePic")

    }

    imagePopOverScene?.transitioningDelegate = self

    self.navigationController?.pushViewController(imagePopOverScene!, animated: true)

}

@IBAction func postBtnAction(sender: UIButton) {

    print("post btn action recieved")
    tableViewConfiguration()

}

func tableViewConfiguration(){



    parentTableView.beginUpdates()

    desc.append(postTextView.text!)
    menProfilePictures.append(UIImage(named: "defaultProfilePic")!)
    queens.append("--")
    lords.append("Anonymous")

    let indexPath : [NSIndexPath] = [NSIndexPath(forRow: 0, inSection: 0)]
    print(indexPath)
    parentTableView.insertRowsAtIndexPaths(indexPath, withRowAnimation: .Fade)

    tableView(parentTableView, cellForRowAtIndexPath: indexPath[0])

    parentTableView.endUpdates()
    parentTableView.reloadData()

    parentTableView.scrollToRowAtIndexPath(indexPath[0], atScrollPosition: UITableViewScrollPosition.Top, animated: true)


}


@IBAction func pickImagesAction(sender: UIButton) {





}

}

1 个答案:

答案 0 :(得分:3)

首先,请勿在调用reloadData后致电insertRowsAtIndexPaths,因为insertRowsAtIndexPaths会隐式重新排列表格视图。

但只是这种情况掩盖了实际问题。

您将新项目附加到数据源数组 - 顺便说一下,为什么不使用自定义结构而不是三个(编辑:那里甚至是四个!)数组 - 所以它们最后是物理

insertRowsAtIndexPaths在索引0处正确插入项目,但随后重新加载表视图会根据数据源数组将项目再次移动到表格的末尾。

解决方案insert数据源数组索引0处的项目,而不是append

修改

建议使用自定义结构

  • 在视图控制器外声明

    struct Avatar {
    
      let lord : String
      let queen : String
      let desc : String
      let profileImage : UIImage?
    
      init(lord: String, queen: String, desc: String, imageName: String) {
        self.lord = lord
        self.queen = queen
        self.desc = desc
        self.profileImage = UIImage(named: imageName)
      }
    }
    
  • ViewController声明一个数据源数组

    var avatars = [Avatar]()
    
  • viewDidLoad填充数据源数组

    override func viewDidLoad() {
        super.viewDidLoad()
        parentTableView.delegate = self
        parentTableView.dataSource = self
    
        avatars = [Avatar(lord: "name1", queen: "--", desc: "alpha", imageName: "DaarioNaharis"),
                   Avatar(lord: "name2", queen: "q1", desc: "beta", imageName: "JaimeLannister"),
                   Avatar(lord: "name3", queen: "q2", desc: "gamma", imageName: "LordVarys")]
        parentTableView.reloadData()
     }
    
  • numberOfRowsInSection返回avatars.count

  • cellForRowAtIndexPath中分配属性

    let avatar = avatars[indexPath.row]
    cell.feedPostUsername.text = avatar.lord
    cell.feedPostUserDetails.text = avatar.queen
    cell.feedPostDescription.text = avatar.desc
    cell.feedUserProfilePictures.image = avatar.profileImage
    
  • tableViewConfiguration替换为

    func tableViewConfiguration(){
        let newAvatar = Avatar(lord: "Anonymous", queen: "--", desc: postTextView.text!, imageName: "defaultProfilePic"
        avatars.insert(newAvatar, atIndex: 0)
        let indexPath = NSIndexPath(forRow: 0, inSection: 0)
        print(indexPath)
        parentTableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        parentTableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true)
    }