Swift: inputAccessoryView buttons are not showing

2019-09-18 04:25发布

问题:

Following is my code for adding an inputAccessoryView (with a Done button on it) to my textView:

let keyboardButtonView = UIToolbar()
keyboardButtonView.sizeToFit()
let doneButton = UIBarButtonItem(image: nil, style: .Done, target: self, action: "closeMessageViewKeyboard")
doneButton.possibleTitles = ["Done"]
var toolbarButtons = NSMutableArray()
toolbarButtons.addObject(doneButton)
keyboardButtonView.items = toolbarButtons as [AnyObject]
messageView.inputAccessoryView = keyboardButtonView

The Done button never appears. All I get is a white accessory bar. Am I missing anything here?

回答1:

For me I create the accessory view using UINavigationBar like this:

let navBar = UINavigationBar(frame: CGRectMake(0, 0, viewWidth, 44))
navBar.barStyle = UIBarStyle.BlackTranslucent;
navBar.backgroundColor = UIColor.blackColor();
navBar.alpha = 0.9;
//replace viewWidth with view controller width
let navItem = UINavigationItem()
let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "closeMessageViewKeyboard")
navItem.rightBarButtonItem = doneButton

navBar.pushNavigationItem(navItem, animated: false)

messageView.inputAccessoryView = navBar


回答2:

1) Add self? self.messageView.inputAccessoryView = keyboardButtonView

2) You should be able to remove this line: doneButton.possibleTitles = ["Done"] and add (title: "done",...) to the line above it.

3) I have similar code and it probably doesn't matter, but, you might add: keyboardButtonView.barStyle = UIBarStyle.Default