简体   繁体   中英

Get data from UIButton in viewForHeaderInSection sent to method in add Target

Updated to be more clear, sorry noob.

I setup a button to appear in a header in each section on a tableview, the button appears and calls the specified function, however I'd like to pass section data to the method that's called.

When I try to use the UIButton.tag or even assign the section title to the button's textLabel title it always comes back as nil (even when the section title shows properly).

I need to pass data to the function so I know what I'm dealing with (I want to use another view controller to add a new piece of data to the rows in that specific section).

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var sectionsDictionary:NSDictionary = ["Fruits" : ["Apple", "Pear", "Plum","Orange","Kiwi","Banana","Grape"], "Veggies" : ["Celery", "Carrots", "Lettuce","Brocoli","Squash"]]

var sectionTitlesArray = []

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    sectionTitlesArray = Array(sectionsDictionary.allKeys)
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {

    return sectionTitlesArray.count
}

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    var headerFrame:CGRect = tableView.frame

    var title = UILabel(frame: CGRectMake(10, 10, 100, 30))
    title.text = sectionTitlesArray.objectAtIndex(section) as? String

    var headBttn:UIButton = UIButton.buttonWithType(UIButtonType.ContactAdd) as UIButton
    headBttn.enabled = true
    headBttn.titleLabel?.text = title.text

    headBttn.addTarget(self, action: "showAddVC:", forControlEvents: UIControlEvents.TouchUpInside)

    var headerView:UIView = UIView(frame: CGRectMake(0, 0, headerFrame.size.width, headerFrame.size.height))
    headerView.addSubview(title)
    headerView.addSubview(headBttn)

    return headerView

}

func showAddVC(sender: UIButton!) {

    println(sender.titleLabel?.text)

}

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

    var headerFloat = CGFloat.abs(20)

    return headerFloat

}

Phew, got it, I was able to use .tag by just using indexOfObject and passing the object at index in section.

headBttn.tag = sectionTitlesArray.indexOfObject(sectionTitlesArray.objectAtIndex(section))

this gives .tag the index of where the button was pressed, which I can use later on. woohoo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM