从自定义tableviewcell

时间:2018-01-25 09:55:09

标签: ios swift uitableview navigation

我在tableview中的自定义tableview单元格中有一个按钮。 我尝试呈现,推送和实例化到另一个视图控制器但是因显示错误而失败:

  

主题1:致命错误:在展开Optional

时意外发现nil

这是我的代码:         console image if required

class ProfileHeaderView: UITableViewCell{

    @IBAction func editProfile(_ sender: Any) {

        let editProfilePage = EditProfileViewController()
        UIApplication.shared.keyWindow?.rootViewController?.present(editProfilePage, animated: true, completion: nil)

    } 

}

我想要移动的页面:

class EditProfileViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    override func viewDidLoad() {
        super.viewDidLoad()

        self.hideKeyboardWhenTappedAround()

        mobileNumber.keyboardType = UIKeyboardType.numberPad **//Error**
    }
}

我也尝试过rootViewController。请帮忙。

Screenshot if required

Updated console after the story board identifier change

2 个答案:

答案 0 :(得分:0)

我用以下代码为自己解决了这个问题 您可以使用协议将tableviewcell内的单击委托给UIViewController 在我的情况下,我确实使用了segues,但您可以直接在EditProfileViewController函数

中实例化cellCallback

代表的代码

protocol CellDelegator {
    func cellCallback(myData dataobject: Item)
}

tableview单元格内的代码

@IBAction func imageClicked(_ sender: UIButton) {
    self.delegate?.cellCallback(myData: (self.cartItem?.item)!)

}

ViewController中的代码

extension MyViewController :  CellDelegator{
    func cellCallback(myData dataobject: Item) {
        performSegue(withIdentifier: "xyz", sender: dataobject)
    }

答案 1 :(得分:0)

<强>说明

崩溃是由行mobileNumber.keyboardType = UIKeyboardType.numberPad引起的,不是因为UIKeyboardType.numberPad,而是因为左侧:mobileNumber.keyboardType。移动号码应该是类型@IBOutlet的{​​{1}}(隐式强制解包UITextField!),当UITextField为零时会导致崩溃。这就是你的情况。

之前有效,因为在您使用segue导航到mobileNumber之前,故事板在EditProfileViewController被调用之前已正确初始化mobileNumber字段。但是,您要在此行上以编程方式创建viewDidLoad实例:EditProfileViewController,这完全绕过了故事板。因此,应该通过故事板连接的字段和操作不会连接起来,从而导致崩溃。

<强>解

使用故事板创建let editProfilePage = EditProfileViewController()的实例,而不是调用初始化程序。这意味着,替换这一行:

EditProfileViewController

有这样的事情:

let editProfilePage = EditProfileViewController()

在这一行中,我假设带有let editProfilePage = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "EditProfileViewController") as! EditProfileViewController 的故事板被命名为EditProfileViewController(当然,如果在其他故事板中定义了Main,则使用该而不是EditProfileViewController故事板那里),另外确保你在故事板中使用Storyboard ID并将其设置为EditProfileViewController(或使用你想要的任何自定义ID):

Setting storyboard ID

相关问题