是否可以将标记设置为BarButtonItem,并在action方法中将其标记为BarButtonItem。
我已尝试过以下代码,但println(btnsSend.tag)
始终打印0。
(UIBarButtonItem.title
有效但我需要设置唯一ID)
func configureToolbar() {
for(var i:Int = 0; i < watchNameArray.count; i++) {
var newBarButtonItem: UIBarButtonItem {
return UIBarButtonItem(title: watchNameArray[i], style: .Plain, target: self, action: "newButton:");
}
toolbarButtonItems += [newBarButtonItem];
newBarButtonItem.tag = i;
}
thisToolBar.setItems(toolbarButtonItems, animated: true)
}
func newButton(sender: UIBarButtonItem) {
var btnsSend:UIBarButtonItem = sender;
println(btnsSend.tag);
}
如何从action方法中捕获特定的按下的UIBarButtonItem。
答案 0 :(得分:0)
您已将newBarButtonItem
定义为...计算的局部变量?我甚至不知道你能做到这一点,所以我很荣幸。但这意味着每次访问它时,都会在大括号中执行代码。也就是说,每条线都会创建一个新的条形按钮项:
// creates a new bar button item and adds it to toolbarButtonItems:
toolbarButtonItems += [newBarButtonItem]
// creates a new bar button item and sets its tag to i:
newBarButtonItem.tag = i
您设置标记的项目与添加到数组的项目完全分开,这就是数组中所有项目tag == 0
的原因。
相反,你想让newBarButtonItem
成为一个实例;然后你可以自定义它并将其添加到数组中。代码的这一部分应如下所示:
var newBarButtonItem = UIBarButtonItem(title: watchNameArray[i], style: .Plain, target: self, action: "newButton:")
newBarButtonItem.tag = i
toolbarButtonItems += [newBarButtonItem]