我是swift和IOS开发的新手,因此我在Xcode中制作了一个Action Sheet,但现在我想从Action Sheet执行操作。我熟悉在ObjC中使用按钮索引,但我似乎无法在swift中解决这个问题。
我还想自定义我的操作表,使文本颜色不同,但这并不重要。如果你能提供帮助,请告诉我。感谢
到目前为止,这是我的代码,但是当按下按钮时,我的Action的.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"
}
}
答案 0 :(得分:1)
你需要:
使您的视图控制器符合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))
}
}
答案 1 :(得分:0)
我认为您的序列不正确,也没有设置委托。
将您的类声明为委托
class ViewController: UIViewController, UIActionSheetDelegate{
...
定义行动表
@IBAction func ActionSheet(sender: UIButton) {
let actionSheet = UIActionSheet(title: "ActionSheet", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: "Done", otherButtonTitles: "A Course", "B Course", "C course")
actionSheet.showInView(self.view)
}
定义代理功能
func actionSheet(actionSheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int)
{
switch buttonIndex{
case 0:
NSLog("Done");
break;
case 1:
NSLog("Cancel");
break;
case 2:
NSLog("A Course");
break;
case 3:
NSLog("B Course");
break;
case 4:
NSLog("C Course");
break;
}
答案 2 :(得分:0)
我创建了一个库,您可以使其像动作表视图一样工作:)