Lucky-K
Lucky-K

Reputation: 47

swift uitoolbar not showing all of the buttons?

In my code, I create a for loop which creates a uibarbuttonitem for all 17 items in my array like this. my array is

let musicalnotes = ["C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B", "E♭", "E","G♭", "A♭", "B♭"]


func createnotes(){

    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
   // toolBar.frame = CGRect(x: toolBar.frame.origin.x, y: toolBar.frame.origin.y, width: toolBar.frame.size.width, height: 900)
    var buttonarray = [UIBarButtonItem]()
    for a in musicalnotes {
        let a = UIBarButtonItem(title: a, style: .plain, target: self, action: #selector(self.addnotetonote(sender:)))

        buttonarray.append(a)
    }
    let cancel = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(self.revert))
    buttonarray.append(cancel)
    toolBar.isTranslucent = true
    toolBar.items = buttonarray

My problem is the toolbar on an iPhone shows the buttons like so:

iphone example

On an iPhone, the buttons are not visible but functioning, but on an iPad it's normal.

Is it because there are too many buttons to fit on the toolbar or something else?

Upvotes: 1

Views: 422

Answers (2)

Lucky-K
Lucky-K

Reputation: 47

I figured it out using the answer above. Here is the solved code.

 toolBar.isUserInteractionEnabled = true
        toolBar.frame = CGRect(x: 0, y: 0, width: 33 * 20, height: toolBar.frame.size.height)
        let scrollView = UIScrollView()
        scrollView.frame = toolBar.frame;
        scrollView.autoresizingMask = toolBar.autoresizingMask;
        scrollView.showsVerticalScrollIndicator = false;
        scrollView.showsHorizontalScrollIndicator = false;
        scrollView.addSubview(toolBar)
        toolBar.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
        toolBar.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
        toolBar.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 0).isActive = true
        toolBar.heightAnchor.constraint(equalToConstant: 44).isActive = true
        notes.inputAccessoryView = scrollView
        notes.reloadInputViews()

Upvotes: 1

Satish
Satish

Reputation: 2043

Add toolBar into a UIScrollView.

scrollView.addSubview(toolBar)

And would recommend using auto layout

toolBar.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
toolBar.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
toolBar.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 0).isActive = true
toolBar.heightAnchor.constraint(equalToConstant: 44).isActive = true

enter image description here

Upvotes: 1

Related Questions