我一般不熟悉Swift和IOS开发,因此我在Xcode中制作了一个动作表,但是现在我想从该动作表中执行动作。我对通过使用按钮Index在ObjC中进行此操作很熟悉,但是我似乎无法迅速弄清楚。
我还想自定义我的“动作表”以使文本具有不同的颜色,但这并不是那么重要。如果您可以提供帮助,请告诉我。谢谢
到目前为止,这是我的代码,但是按下按钮时,动作的.tag部分是错误的...
@IBAction func ActionSheet(sender: UIButton) {
var sheet: UIActionSheet = UIActionSheet();
let title: String = "Action Sheet!";
sheet.title = title;
sheet.addButtonWithTitle("Cancel");
sheet.addButtonWithTitle("A course");
sheet.addButtonWithTitle("B course");
sheet.addButtonWithTitle("C course");
sheet.cancelButtonIndex = 0;
sheet.showInView(self.view);
}
func actionSheet(sheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int) {
if (actionSheet.tag == 1) {
NameLabel.text = "I am confused"
}
}
最佳答案
你需要:
使您的视图控制器符合UIActionSheetDelegate
协议:class ViewController: UIViewController, UIActionSheetDelegate {
添加self
作为代理,并将标签设置为1:
var sheet: UIActionSheet = UIActionSheet()
let title: String = "Action Sheet!"
sheet.title = title
sheet.addButtonWithTitle("Cancel")
sheet.addButtonWithTitle("A course")
sheet.addButtonWithTitle("B course")
sheet.addButtonWithTitle("C course")
sheet.cancelButtonIndex = 0
sheet.delegate = self // new line here
sheet.tag = 1 // another new line here
sheet.showInView(self.view)
现在您可以使用
buttonIndex
:func actionSheet(sheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int) {
if sheet.tag == 1 {
println(buttonIndex)
println(sheet.buttonTitleAtIndex(buttonIndex))
}
}