UIToolbar больше не отображается при закрытии клавиатуры в Swift

У меня есть UIToolbar, содержащий UITextField. Я хочу показать панель инструментов над клавиатурой, а затем снова отобразить ее, когда закончу редактирование внутри текстового поля.

Проблема в том, что он работает при выборе текстового поля. Однако панель инструментов исчезает из вида при скрытии клавиатуры. Что нужно сделать, чтобы снова отобразить его на мой взгляд?

Мой код Swift: Добавить UITextFieldDelegate

class ATCChatThreadViewController: MessagesViewController, MessagesDataSource, MessageInputBarDelegate, UITextFieldDelegate {

Создать панель инструментов, как показано ниже.

 func createToolbar(){

        //Fixed space
        let fixed = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.fixedSpace, target: self, action: nil)
        fixed.width = 10

        //Camera
        //let img = UIImage(named: "camera-filled-icon")!.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
        let img = UIImage.localImage("camera-filled-icon", template: true)
        let iconSize = CGRect(origin: CGPoint.zero, size: CGSize(width: 30, height: 30))
        let iconButton = UIButton(frame: iconSize)
        iconButton.setTitleColor(uiConfig.primaryColor, for: .normal)
        iconButton.setBackgroundImage(img, for: .normal)
        let cameraItem = UIBarButtonItem(customView: iconButton)
        cameraItem.tintColor = uiConfig.primaryColor
        iconButton.addTarget(self, action: #selector(cameraButtonPressed), for: .touchUpInside)

        //TextField true
        textFieldChat = UITextField(frame: CGRectMake(0,0,(self.view.frame.size.width - 100) ,30))
        textFieldChat.tintColor = uiConfig.primaryColor
        textFieldChat.textColor = uiConfig.inputTextViewTextColor
        textFieldChat.backgroundColor = uiConfig.inputTextViewBgColor
        textFieldChat.layer.cornerRadius = 14.0
        textFieldChat.layer.borderWidth = 0.0
        textFieldChat.font = UIFont.systemFont(ofSize: 16.0)
        textFieldChat.delegate = self
        textFieldChat.attributedPlaceholder = NSAttributedString(string: "Start typing...".localized(), attributes: [NSAttributedString.Key.foregroundColor: uiConfig.inputPlaceholderTextColor])

        let paddingView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 20))
        textFieldChat.leftView = paddingView
        textFieldChat.leftViewMode = .always
        let textFieldButton = UIBarButtonItem(customView: textFieldChat)

        //Fixed space
        let fixedTwo = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.fixedSpace, target: self, action: nil)
        fixedTwo.width = 10

        //Send Button
        let imgSend = UIImage.localImage("share-icon", template: true)
        let iconSendSize = CGRect(origin: CGPoint.zero, size: CGSize(width: 30, height: 30))
        let sendButton = UIButton(frame: iconSendSize)
        sendButton.setTitleColor(uiConfig.primaryColor, for: .normal)
        sendButton.setBackgroundImage(imgSend, for: .normal)
        let sendItem = UIBarButtonItem(customView: sendButton)
        sendItem
            .tintColor = uiConfig.primaryColor
        sendButton.addTarget(self, action: #selector(sendBtnPressedWith), for: .touchUpInside)

        //Flexible Space
        //        let flexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: self, action: nil)
        let flexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.fixedSpace, target: self, action: nil)
        flexible.width = 10

        //Toolbar
        var bottomsafeAreaHeight: CGFloat?
        if #available(iOS 11.0, *) {
            bottomsafeAreaHeight = UIApplication.shared.windows.first{$0.isKeyWindow }?.safeAreaInsets.bottom ?? 0
        } else {
            // Fallback on earlier versions
            bottomsafeAreaHeight = bottomLayoutGuide.length
            bottomsafeAreaHeight = UIApplication.shared.keyWindow?.rootViewController?.bottomLayoutGuide.length ?? 0
        }

        toolbar = UIToolbar(frame: CGRectMake(0,(self.view.frame.size.height - 116 - (bottomsafeAreaHeight ?? 0)),view.frame.width,50))
        toolbar.sizeToFit()
        toolbar.barTintColor = UIColor.f5f5f5ColorBg()
        toolbar.isTranslucent = false
        toolbar.tintColor = uiConfig.primaryColor
        toolbar.items = [fixed, cameraItem, fixed, textFieldButton,fixedTwo, sendItem,flexible]
        view.addSubview(toolbar)
    }



   // MARK: - UITextFieldDelegate

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    textFieldChat.inputAccessoryView = toolbar
    return true
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
     view.addSubview(toolbar)
     self.toolbar.isHidden = false
     return true
}

person Iphone User    schedule 07.03.2020    source источник


Ответы (1)


если только чат etxfield использует панель инструментов, замените строку:

view.addSubview(toolbar)

с

textFieldChat.inputAccessoryView = toolbar

удалите оба метода textFieldShouldBeginEditing и textFieldShouldEndEditing

person Van    schedule 07.03.2020
comment
Привет @Van, если я удалю строку view.addSubview(панель инструментов), то ничего не будет показано, так как 3 элемента (камера, текстовое поле и отправка) находятся внутри панели uitoolbar. Я использую uitabbar, и мне нужно, чтобы они по умолчанию отображались над панелью вкладок и перемещались с помощью клавиатуры, когда текстовое поле начинает редактироваться. - person Iphone User; 08.03.2020