【问题标题】:Get data from UIButton in viewForHeaderInSection sent to method in add Target从 viewForHeaderInSection 中的 UIButton 获取数据发送到 add Target 中的方法
【发布时间】:2014-10-05 22:20:08
【问题描述】:

更新更清晰,对不起菜鸟。

我设置了一个按钮出现在表格视图的每个部分的标题中,该按钮出现并调用指定的函数,但是我想将部分数据传递给被调用的方法。

当我尝试使用 UIButton.tag 甚至将部分标题分配给按钮的 textLabel 标题时,它总是返回为 nil(即使部分标题正确显示)。

我需要将数据传递给函数,以便我知道我在处理什么(我想使用另一个视图控制器将一条新数据添加到该特定部分的行中)。

类 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

}

【问题讨论】:

  • 那么你的按钮函数被调用了吗?您的 addRoom 代码在哪里?
  • 对不起,它真的应该是 showAddVC,已修复。我在那里有很多东西,但做了一个新项目以使其更容易临时使用。
  • 然后你的函数被调用了?请更具体,并在此处删除所有发布的无用(回答问题)代码。
  • 是的,该函数被调用并执行 println() - 但我在发送者(UIButton)上调用的任何内容都显示为零。我无法向 AddTarget 添加参数,并且我读到我也不能在那里使用闭包。我需要跟踪按钮被触及的部分。
  • 让它更干净

标签: ios uitableview swift uibutton


【解决方案1】:

唷,明白了,我可以通过使用 indexOfObject 并在节中的索引处传递对象来使用 .tag。

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

这为 .tag 提供了按钮按下位置的索引,我稍后可以使用它。哇哦。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 2023-03-09
    • 2023-04-09
    相关资源
    最近更新 更多