フリープログラマー日記

iOS,アンドロイド開発を気ままにしながら生きてるおじさんのブログです。

第34回 removeFromSuperview()でハマる

 氏名入力をするために、スクロールビューのボタンから、氏名を入力する画面になっています。次に名前を登録のボタンを押したら、スクロールビューに名前が入り、全画面に戻るというのが私のシナリオですが・・・

f:id:momonga117:20180601205646p:plain

 なんということでしょう。
名前を登録ボタンの飛び先のコードにremoveFromSuperview()と書くと、Thread 1:signal SIGABRTというエラーメッセージが出て、怒られてしまいました。コンパイルは通るが実行時に不具合が生じるとよくこのエラーになるようです。しかも、このエラーの対処がなかなか見つからない・・・
なんども言います。素人なんです、私。エラーログ読んだりとかしないので。

そこで、原因を考えてみると、オブジェクトとして、NameInputViewがあり、そこにボタンの記述やらボタン処理やら書いています。そのボタン処理の中で、NameInputViewのインスタンスを、removeFromSuperview()・・・
と、ここで、処理中のプログラムが消えてしまうってのが、原因らしい。
走っている電車の前にあるレールを取っ払うみたいなことをしてた。これはまずいです。
 そこで、急遽、Teamクラスにコードを置き、Teamクラスの中から、消すことにしました。

こんな感じです。

    public func makeNameInputView() {
        
        let view: UIView = UIView(frame: MySettings.getFullFrame())
        view.backgroundColor = UIColor(red: 0, green: 155/255, blue: 155/255, alpha: 220/255)
        view.tag = MySettings.Entry.NameInputArea
        self.view.addSubview(view)
        
        
        // 走者名を登録します
        let infomation: UILabel = UILabel(frame:MySettings.Entry.imfomationFrame())
        infomation.text = "走者名を登録します"
        infomation.textAlignment = .center
        infomation.backgroundColor = UIColor.white
        view.addSubview(infomation)
        //入力用textField
        let nameField: UITextField = UITextField(frame: MySettings.Entry.nameFieldFrame())
        nameField.backgroundColor = UIColor.white
        view.addSubview(nameField)
        nameField.resignFirstResponder()
        
        //OKボタン
        let okButton: UIButton = UIButton(frame: MySettings.Entry.okButtonFrame())
        okButton.setTitle("名前を登録", for: .normal)
        okButton.setTitleColor(UIColor.black, for: .normal)
        okButton.backgroundColor = UIColor.lightGray
        okButton.tag = MySettings.Entry.OkButtonTag
        okButton.addTarget(self, action: #selector(onClick), for: UIControlEvents.touchUpInside)
        view.addSubview(okButton)
        
        //キャンセルボタン
        let cancelButton: UIButton = UIButton(frame: MySettings.Entry.cancelButtonFrame())
        cancelButton.setTitle("キャンセル", for: .normal)
        cancelButton.setTitleColor(UIColor.black, for: .normal)
        cancelButton.backgroundColor = UIColor.lightGray
        cancelButton.tag = MySettings.Entry.CanselButtonTag
        cancelButton.addTarget(self, action: #selector(onClick), for: UIControlEvents.touchUpInside)        
        view.addSubview(cancelButton)
        
        nameField.becomeFirstResponder()
    }
    
    // ボタンの動作
    @objc func onClick(sender: UIButton) {
        if sender.tag == MySettings.Entry.OkButtonTag {
            // OKボタンの時だけ、新規のメンバーを作成
        }
        let view = self.view.viewWithTag(MySettings.Entry.NameInputArea)
        view?.removeFromSuperview()
    

途中のaddTargetの書式、action: #selector(onClick)っていうところ、昔の本と違いますよね。なんか面倒になってます。

ま、これで、無事消えることとなりました。