4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

はじめに

今回はInputAccessoryViewというものを使って、以下のようなものを作ってみます。

ezgif.com-gif-maker (1).gif

実装

以下のように、textViewとbuttonをおいたInputAccessoryView.xibを作ります。
スクリーンショット 2021-04-26 14.53.51.png

そしてInputAccessoryView.swiftに以下のようにコードを記述します。

import UIKit

final class InputAccessoryView: UIView {

    @IBOutlet private weak var textView: UITextView!
    @IBOutlet private weak var sendButton: UIButton!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        loadNib()
        setupViews()        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

// MARK: - setup nib
private extension InputAccessoryView {
    func loadNib() {
        let nib = UINib(nibName: String(describing: InputAccessoryView.self), bundle: nil)
        guard let view = nib.instantiate(withOwner: self,
                                         options: nil).first as? UIView else { return }
        view.frame = self.bounds
        self.addSubview(view)
    }
}

// MARK: - setup views
private extension InputAccessoryView {
    func setupViews() {
        textView.layer.cornerRadius = 15
        sendButton.layer.cornerRadius = 15
    }
}

次に、xibとswiftファイルを紐付けします。以下のように、File's OwnerのClassを先ほど実装したInputAccessoryViewにします。
スクリーンショット 2021-04-26 14.57.17.png

ここで、File's Ownerのこちらの画面が黄色くなっている場合はIBOutletを接続し直しましょう。
スクリーンショット 2021-04-26 14.59.07.png

そして、最後にViewControllerを以下のように実装してみます。

import UIKit

final class ViewController: UIViewController {
    
    private var myInputAccessoryView: InputAccessoryView = {
        let view = InputAccessoryView()
        view.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: 60)
        return view
    }()
    override var inputAccessoryView: UIView? { myInputAccessoryView }
    override var canBecomeFirstResponder: Bool { true }
    
}

これで先ほどのようなキーボードの上にtextViewとbuttonが表示されてくれるはずです。

ドキュメント
参考

おわりに

こんな便利なものがあったとは、、、

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?