I’m not getting the syntax right. Anybody know what's missing here? I’m using Xcode 6 beta 3 and I'm trying to dynamically add a toolbar item to my (manually added) toolbar in my viewDidLoad. There are two issues. First, I can't append the items in my toolbar to an array. Second, while the compiler allows my call to append (+=), when it finishes, the array is still empty.
override func viewDidLoad() {
super.viewDidLoad()
var items = [AnyObject]() // Zero items, mutable, right?
// items += buttonBar.items // Not allowed --> compiler error
if let displayModeButton = self.splitViewController.displayModeButtonItem() {
items += displayModeButton // Still zero items after append
}
buttonBar.items = items // Still zero items after append
}
buttonBar is an IBOutlet that is set in IB.
I was able to add the toolbar's items by force unwrapping the array. It seems like that shouldn't be necessary, since the items property is implicitly unwrapped, but that made the compiler let it through.
I'm not sure why your items += displayModeButton line isn't working -- are you sure it's being called? This code adds a button with the title "Another" to my toolbar:
var items = [AnyObject]()
items += self.barButton.items!
items += UIBarButtonItem(title: "Another", style: .Plain, target: nil, action: "")
self.barButton.items = items
Below code worked for me:
let keyboardDoneButtonView = UIToolbar()
keyboardDoneButtonView.sizeToFit()
let flexBarButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil)
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("doneClicked"))
var items = [UIBarButtonItem]()
items.append(flexBarButton)
items.append(doneButton)
keyboardDoneButtonView.items = items
Hope this helps!!
Related
I want to hide/show a UIBarButtonItem when a segmentedControl changes, this is my code:
#objc fileprivate func handleSegmentedChange() {
switch segmentedControl.selectedSegmentIndex {
case index0:
// Set the proper rightBarButtonItems, in the first load this bar button items will be nil, this is why we have to check first
self.navigationItem.rightBarButtonItems?.append(UIBarButtonItem(image: #imageLiteral(resourceName: "Filter2"), style: .plain, target: self, action: #selector(openBottomSheet)))
default:
self.navigationItem.rightBarButtonItems?.remove(at: 0)
}
}
However is not updating the views (hiding or showing anything).
Note I've also tried setting the rightBarButtonItems to nil before adding or removing items, however is not working.
How can I accomplish the desired effect?
If rightBarButtonItems is nil before you try to append or remove items to/from it, then nothing will happen as you cannot append or remove items to/from a non-existent array.
Instead of appending/removing to/from rightBarButtonItems, try just setting it directly to the items you want it to be, like this:
#objc fileprivate func handleSegmentedChange() {
switch segmentedControl.selectedSegmentIndex {
case 0:
let barButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "Filter2"),
style: .plain,
target: self,
action: #selector(openBottomSheet))
navigationItem.rightBarButtonItems = [barButtonItem]
// Note: If you're just dealing with one bar button item,
// you could also just use `navigationItem.rightBarButtonItem` like:
// navigationItem.rightBarButtonItem = barButtonItem
default:
navigationItem.rightBarButtonItems = nil // or `= []`
// Note: If you're just dealing with one bar button item,
// you could also just use `navigationItem.rightBarButtonItem` like:
// navigationItem.rightBarButtonItem = nil
}
}
I am developing a TODOList(iOS application) but there is a problem i.e. how can I add dropdown list is uicollectionview cell.
Means when view did load, collection view loaded, there should be a dropdown in every single cell
There's no any inbuilt dropdown functionality in iOS but you can do it by using UITableView or by using 3rd party library.
I suggest you to try this. DropDown
define this globally.
let dropDown = DropDown()
If you want to customise dropDown you can use this.
func customizeDropDown() {
DropDown.appearance().cellHeight = 40
DropDown.appearance().backgroundColor = UIColor.white
DropDown.appearance().selectionBackgroundColor = Colors.purpleColor
DropDown.appearance().cornerRadius = 5
DropDown.appearance().textColor = Colors.NavTitleColor
DropDown.appearance().shadowColor = (UIColor.init(hexString: "1AD691")?.withAlphaComponent(0.0))!
DropDown.appearance().shadowOpacity = 0.9
DropDown.appearance().shadowRadius = 0
DropDown.appearance().animationduration = 0.25
}
In cellForItemAt you need to add action on your dropdown button like this.
cell.btnDropdown.tag = indexPath.item
cell.btnDropdown.addTarget(self, action: #selector(btnDropDownTapped), for: .touchUpInside)
Once you tapped on any button from UICollectionViewCell below method will call where you need to pass anchorView.
#IBAction func btnDropDownTapped(_ sender: UIButton) {
self.dropDown.anchorView = sender // The view to which the drop down will appear on
self.dropDown.bottomOffset = CGPoint(x: 0, y: sender.bounds.height) //Top of drop down will be below the anchorView
self.dropDown.dataSource = ["First", "Last", "Second", "Third"] // Static array you need to change as per your requirement
self.dropDown.selectionAction = { [unowned self] (index, item) in
print(item) // **NOTE: I AM JUST PRINTING DROPDOWN SELECTED VALUE HERE, YOU NEED TO GET `UICollectionViewCell` HERE YOU NEED TO SET VALUE INSIDE CELL LABEL OR YOU CAN SET SELECTED DROPDOWN VALUE IN YOUR MODEL AND RELOAD COLLECTIONVIEW**
self.collectionView.reloadData()
}
self.dropDown.show()
}
If you have UITextField in your UICollectionViewCell then you can try this code inside textFieldShouldBeginEditing delegate.
NOTE: I AM JUST PRINTING DROPDOWN SELECTED VALUE HERE, YOU NEED TO GET UICollectionViewCell HERE YOU NEED TO SET VALUE INSIDE CELL LABEL OR YOU CAN SET SELECTED DROPDOWN VALUE IN YOUR MODEL AND RELOAD COLLECTIONVIEW
iOS doesn't have any native control for drop downs.You can use pickers instead.
See like below :
Here is the code to add pickerView.
let picker: UIPickerView
picker = UIPickerView(frame: CGRectMake(0, 200, view.frame.width, 300))
picker.backgroundColor = .whiteColor()
picker.showsSelectionIndicator = true
picker.delegate = self
picker.dataSource = self
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.Default
toolBar.translucent = true
toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "donePicker")
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "donePicker")
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true
textField1.inputView = picker
textField1.inputAccessoryView = toolBar
There are lots of libraries added to github for cool picker controls:
Actionsheet PickerView
Selectionmenu
Please follow steps to perform your operation
Add UITableView in UICollectionViewCell.
Make the hidden property of UITableView to true
collectionViewCell.dropDownTableView.isHidden=true
When the user select option to display dropdown, reload UITableView data and set hidden property of UITableView to false.
How to add UITableView to UICollectionViewCell
I've been trying to implement this toolbar, where only the 'Next' button is enabled when the top textField is the firstResponder and only the 'Previous' button is enabled when the bottom textField is the firstResponder.
It kind of works, but i need to execute my own code by accessing previous, next and done buttons action methods in other classes(like delegates)
Thanks in advance for your suggestions..
extension UIViewController {
func addInputAccessoryForTextFields(textFields: [UITextField], dismissable: Bool = true, previousNextable: Bool = false) {
for (index, textField) in textFields.enumerated() {
let toolbar: UIToolbar = UIToolbar()
toolbar.sizeToFit()
var items = [UIBarButtonItem]()
if previousNextable {
let previousButton = UIBarButtonItem(image: UIImage(named: "Backward Arrow"), style: .plain, target: nil, action: nil)
previousButton.width = 30
if textField == textFields.first {
previousButton.isEnabled = false
} else {
previousButton.target = textFields[index - 1]
previousButton.action = #selector(UITextField.becomeFirstResponder)
}
let nextButton = UIBarButtonItem(image: UIImage(named: "Forward Arrow"), style: .plain, target: nil, action: nil)
nextButton.width = 30
if textField == textFields.last {
nextButton.isEnabled = false
} else {
nextButton.target = textFields[index + 1]
nextButton.action = #selector(UITextField.becomeFirstResponder)
}
items.append(contentsOf: [previousButton, nextButton])
}
let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: view, action: #selector(UIView.endEditing))
items.append(contentsOf: [spacer, doneButton])
toolbar.setItems(items, animated: false)
textField.inputAccessoryView = toolbar
}
}
}
I am calling this from other class as :
let field1 = UITextField()
let field2 = UITextField()
addInputAccessoryForTextFields([field1, field2], dismissable: true, previousNextable: true)
Although I'm not 100% convinced I understand your question, here goes:
From other classes, you want to call the actions of your buttons, but your actions are set to UITextField.becomeFirstResponder and UIView.endEditing.
Rather than call these methods directly, create your own methods the actions should call, and put these calls into those methods.
In addInputAccessoryForTextFields(...) change the previousButton's target and action to:
previousButton.target = self
previousButton.action = #selector(handlePreviousButton)
Now add the new method:
#objc func handlePreviousButton()
{
// you'll need to associate the previous button to a specific text field
// and hang onto that association in your class, such as in a property named textFieldRelatedToPreviousButton.
self.textFieldRelatedToPreviousButton.becomeFirstResponder()
}
Now you can call handlePreviousButton() directly from elsewhere in your class, if you wish, or even from other classes.
Update
I just noticed you're extending UIViewController. So you can't add storage by adding a property. You can add storage via objc_setAssociatedObject and then get it via objc_getAssociatedObject, however, to get around this. See this SO or this SO for details on that. So you can, for example, "attach" the textField to your previousButton so that you can access it via the handlePreviousButton() method you add to your extension. And you can pass in the previousButton as a parameter (the sender) to handlePreviousButton() too.
Update 2
Another approach to consider is to use the button's tag property to store the tag value of the related textField. (i.e. each button and its related textField would have the same tag value). So in handlePreviousButton(sender:UIBarButtonItem) you loop through all the UITextField children of your self.view and locate the one whose tag matches sender.tag . Then you can do what you need to that UITextField.
I'm currently working on a snapchat-like menu where clicking the left and right UIBarButtonItem makes the screen go in their respective directions.
TL;DR - I'm wondering if there's a (clean) built-in way of passing through a tag as an Optional type to avoid crashes.
override func viewDidLoad() {
super.viewDidLoad()
// Other setup code here
let leftButton = UIBarButtonItem(title: leftButtonString, style: UIBarButtonItemStyle.Plain, target: self, action: "navButtonClicked:")
let rightButton = UIBarButtonItem(title: rightButtonString, style: UIBarButtonItemStyle.Plain, target: self, action: "navButtonClicked:")
// These tags are not a good solution because they aren't optionals!
leftButton.tag = 0
rightButton.tag = 1 // this isn't necessary, but I don't want it to crash...
// More setup here
}
func navButtonClicked(sender: UIBarButtonItem) {
// Goes right by default
let currentX = self.parentScrollView!.contentOffset.x
var screenDelta = self.parentScrollView!.frame.width
if sender.tag == 0 {
screenDelta *= -1
}
UIView.animateWithDuration(0.5, animations: {() in
self.parentScrollView!.contentOffset = CGPoint(x: currentX + screenDelta, y: 0)
})
}
My current solution works, I'm just working towards writing cleaner code.
Thanks!
Option 1:
Create two properties in your view controller that correspond to each UIBarButtonItem. This way you'll be able to tell which one was tapped.
Option 2:
Sublass UIBarButtonItem and add a property that you want.
I am using a UITableView with static cells to show a form with several UITextFields (each with a unique ordered tag from 9000 to 9015).
When i select a UITextField, the keyboard shows up with a UIToolbar that has 2 buttons, previous and next. The buttons work fine as long as the previous or next UITextField is drawn on screen, otherwise i can not select it because viewWithTag can't find the Field.
DEMO: http://s15.postimg.org/5xjsoiupl/ezgif_com_video_to_gif.gif
EDIT: I tryed using IQKeyboardManagerbut it has the same bug. If the cells are not visible then they are not detected so the next or previous arrow is disabled...
UITextFields
let numberToolbar = UIToolbar(frame: CGRectMake(0, 0, self.view.frame.size.width, 50))
numberToolbar.barStyle = UIBarStyle.Default
numberToolbar.tintColor = color_green
prev_keyboard_button = UIBarButtonItem(title: "Previous", style: UIBarButtonItemStyle.Plain, target: self, action: "keyboardPrevButtonTapped:")
next_keyboard_button = UIBarButtonItem(title: "Next", style: UIBarButtonItemStyle.Plain, target: self, action: "keyboardNextButtonTapped:")
numberToolbar.items = [
prev_keyboard_button,
next_keyboard_button,
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "OK", style: UIBarButtonItemStyle.Plain, target: self, action: "keyboardOKButtonTapped:")]
numberToolbar.sizeToFit()
// bind vars
var_input_name.inputAccessoryView = numberToolbar
var_input_name.delegate = self
var_input_name.tag = 9000 // 9000 + index (0,1,2,3,..)
...
Previous and next code:
func textFieldDidBeginEditing(textField: UITextField) {
// current tag
current_input_tag = textField.tag
// check if it is the first
prev_keyboard_button.enabled = !(textField.tag == 9000)
// check if it is the last
next_keyboard_button.enabled = !(textField.tag == 9015)
}
func keyboardPrevButtonTapped(sender: UIBarButtonItem) {
if current_input_tag > 9000 {
// find next input
if let input = self.view.viewWithTag(current_input_tag - 1) as? UITextField {
input.becomeFirstResponder()
}
}
}
func keyboardNextButtonTapped(sender: UIBarButtonItem) {
if current_input_tag < 9015 {
// find next input
if let input = self.view.viewWithTag(current_input_tag + 1) as? UITextField {
input.becomeFirstResponder()
}
}
}
Is there a way to always draw the static cells or should i be implementing this differently?
if the sell is out of the screen it will be released. It's no matter if you use static or dynamic cells. Probably views you try to find is not exists at this moment