2014-06-13 23 views
8

Chương trình của tôi biên dịch thành công, nhưng khi tôi nhấn nút, nó bị treo. Đây là viewController.swift:EXC_BAD_ACCESS khi cố gắng khởi tạo UIActionSheet trong Swift

import UIKit 

class ViewController: UIViewController, UIActionSheetDelegate{ 

@IBOutlet var button:UIButton 

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

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 


@IBAction func buttonPressed(AnyObject) { 
    let choice = UIActionSheet(title: "Select source", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil, otherButtonTitles:"camera", "libary") 
    choice.showInView(self.view) 
} 
} 

Các lỗi xuất hiện trên dòng này:

let choice = UIActionSheet(title: "Select source", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil, otherButtonTitles:"camera", "library") 

Và đây là văn bản lỗi:

EXC_BAD_ACCESS (mã = 2, địa chỉ = 0x0)

Tôi đã thử chuyển sang chế độ var, chạy nó trên các trình mô phỏng khác nhau, nhưng kết quả là giống nhau.

Trả lời

6

Đã cố gắng nhưng không thể tìm ra ngoại lệ. Cuối cùng tôi nhận được một giải pháp như thế này:

var myActionSheet:UIActionSheet = UIActionSheet() 

     var title : String? = "Select Source" 
     myActionSheet.title = title 
         myActionSheet.delegate = self 
     myActionSheet.addButtonWithTitle("camera") 
     myActionSheet.addButtonWithTitle("Library") 
     myActionSheet.addButtonWithTitle("Cancel") 

     myActionSheet.cancelButtonIndex = 2 
     myActionSheet.showInView(self.view) 

UIActionSheet Đại biểu

func actionSheet(myActionSheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int){ 
     println("the index is %d", buttonIndex) 
    } 
+1

Cảm ơn bạn, nó hoạt động! Btw, tôi đã thay đổi "var" thành "let" và nó cũng hoạt động! – Roman

+0

Hmm, actionSheet (myActionSheet: UIActionSheet !, clickButtonAtIndex buttonIndex: Int) không hoạt động. Mã là như nhau, nhưng tôi thêm những dòng này vào việc thực hiện lớp. – Roman

+0

Kiểm tra các đại biểu đúng cách. chạy vào mã này và sau đó chỉ tôi đăng –

0

Bạn phải kết thúc otherButtonTitles thông số với con số không. Ví dụ: trong trường hợp của bạn, cần phải:

otherButtonTitles:"camera", "libary", nil 

Nó không phải là Swift cụ thể, cũng giống như trong mục tiêu-c.

Các vấn đề liên quan