iOS: Good way to pass value from image button to func in the class - ios

Initially I had two buttons with titles: "+" and "-". Both buttons are located in table cell. I have used protocol and delegate to pass value from button title to function call which depends on input params. If input parameter is "-" - decrease value, if "+" - increase.
But later I removed titles and replaced buttons with respective images. And here I faced an issue - I cannot call function properly because title is blank.
I have implemented the following workaround. I have set Accessibility Identifier for both buttons. For example for +:
And in cell class I used accessibilityIdentifier:
#IBAction func didPressOrderCellButton(_ sender: UIButton) {
cellDelegate?.didPressOrderCellButton(order: order!, menuItem: menuItem!, action: sender.accessibilityIdentifier!)
}
But... I have some doubts if it's proper way to do this. Will it create any issues in future if I decide to work with accessibility feature?
I do not want to use title and add code to ViewController class to hide it every time view is loaded or appeared. I want to avoid such solutions in my code because it's too difficult to support such solutions I believe.
I have tried to find another button identifier that I can use, but didn't succeed.

The simple approach would be just set the tag value inside your button and then check the same tag value and perform your operation Plus or Minus accordingly.
For instance:-
if sender.tag == 0 {
//Do minus
} else if sender.tag == 1 {
//Do plus
}

Related

IOS Swift IBAction behaviour when combining actions

I have a custom keyboard extension which works as expected but I am coming across some odd behaviour which I can't explain. It is designed primarily for data input into Excel spreadsheets, so the fewer the keystrokes the better.
I have 2 IBActions.
Keypressed takes the value of the keypresses and inserts it into the current cell.
Returnpressed emulates the enter key which moves the cursor onto the next cell.
These work as described above, which is all good, but I am now trying to combine the actions, so that the user only has to press the first key and it inserts the text and then moves onto the next cell.
So when I simply extend the code in the Keypressed IBAction to include the code in the Returnpressed action, it simply inserts a carriage return into the text and stays in the same cell.
What am I missing please?
Here is a code snippet:
extension UIKeyInput{
func `return`() -> Void{
insertText("\n")
}
}
class KeyboardViewController: UIInputViewController, AVAudioPlayerDelegate {
#IBAction func KeyPressed(_ sender: Any) {
let string = (sender as AnyObject).titleLabel??.text
(textDocumentProxy as UIKeyInput).insertText("\(string!)")
**//THIS IS THE LINE THAT FIXED THIS FOR ME
textDocumentProxy.adjustTextPosition(byCharacterOffset: -1)**
self.EnterPressed(nil)
}
#IBAction func EnterPressed(_ sender: Any?) {
//default action for a return key press
textDocumentProxy.return()
}
I think you need to override the UITextInputDelegate textDidChange method (UIInputViewController implements UITextInputDelegate).It turns out that textDidChange is called when the text changes. And make the first responder to the next text field of your cell.
I managed to fudge this by determining what action s caused textDidChange to fire. It turns out that by simply adjusting the cursor portion, between inserting the text and firing the Return action works.
Not really sure how, but achieves what I want without the the user knowing it is a kludge and no overhead. I have changed the original code snippet to show the fix.

Swift Radio Buttons - CheckBoxes - Swift 3

I work on Swift 3, and I'm trying to make checkboxes that behave like radio buttons. I explain myself : I have 8 buttons ; each has an "unchecked" image and a "checked" image. I want only 1 button to be selected (so, showing ITS "checked" image) at the time. The principle of radio buttons.
So I tried using the #IBAction with each button, I've this :
#IBAction func tona1_changed(_ sender: Any) {
if test_tona1.isSelected == true
{
test_tona1.setBackgroundImage(UIImage(named: "0b_unchecked"), for: UIControlState.normal)
test_tona1.isSelected = false
}
else
{
test_tona1.setBackgroundImage(UIImage(named: "0b_checked"), for: UIControlState.normal)
test_tona1.isSelected = true
}}
It actually make the image switch between "uncheck" and "check" but I don't know at all how to make it interact with the other buttons.
I tried using an array with the buttons's tags inside but I didn't have something working. I also tried to make a class but I don't know how it can work.
Thanks!
You can achieve that in several ways. One of the most trivial would be to:
Have a datasource. Most of the time an array.
Create an UIButton for each item in your datasource, and insert each button into another array. Each button would have a tag corresponding at the
index of the array. Also set different images for selected state and normal.
Add an action for each button, with the target function being something like:
func buttonPressed(sender:UIButton) {
for button in buttons {
button.isSelected = false
// deselect your model datasource[button.tag]
}
sender.isSelected = true
// select your model datasource[button.tag]
}
I leave the abstraction / improvements / safety to you. The key point is just to use a collection of buttons, iterate through them, and select / deselect them accordingly, and not using a big if/else checking for the button tag everytime.

A UIButton is pressed in 1 VC and I need it to save the buttons title to a label in a different view controller not directly segued to each other

In the initial set up of my app I need the user to chose a genre type. i have it set up such that the user selects from a list of UIButtons which are all different genre types. I need this genre selection to save to the users profile. The next view controller is the same set up as the genreVC but asking for instrument instead of genre. The next segue from here is to view controller 3 the usersVC profile and it should have saved which two buttons were selected on the previous two VC's by updating a label. I have tagged each button with a number and have tried next to everything.
How do I save which button has been pressed on a different view controller to the users profile and update the label on the users profile to the name of the button pressed?
I am using each button individually and have them tagged as such as seen here:
#IBAction func popGenreButton(sender: UIButton) {
if(sender.tag == 6){
print("Pop genre selected")
}
}
#IBAction func altGenreButton(sender: UIButton) {
if(sender.tag == 7){
print("Alternative genre selected")
}
}
#IBAction func electronicGenreButton(sender: UIButton) {
if(sender.tag == 8){
print("Electronic genre selected")
}
}
I also tried adding each button into genreSelection as shown below that didn't work so I stuck with the individual buttons above.
#IBAction func genreSelectionButton(sender: UIButton) {
print(sender.titleLabel!.text!)
genreResult.text = genreString + " genre has been saved to your profile"
}
I also created a nib with myModalDelegate and protocol and nope.
I thought maybe I could create a genre array and when a certain button is selected it calls a certain item from the array and updates that item to the label but I was unsure how to go about this too.
I am using Xcode 7 and Swift 2.0 and Parse as my cloud server.
As you can see I have a lot to learn yet with Swift. I have been searching how to do this for the past week and can't figure it out. I am a 'lot' out of my depth but want to figure it out, if anyone can help that would be great!
A simple solution would be something like creating a global store for those values
i.e.
struct Choices {
static var genre: String?
static var instruments: String?
}
then you could in your different view controllers write and read from it by simply
Choices.instrument = "trumpet"
or
label.text = Choices.genre
A prettier solution would be to create a similar class as the previous struct but not have the variables static. You could then pass it along and fill up with the values from each VC and use the values in the last VC where you are setting the label text

Comparing strings within buttons in swift

I'm implementing a favourite button in swift for my quote application. Since I want to disable the user to be able to favourite a quote twice. I must change the text to unlike and then compare the button text mode being unlike to the button text mode being like. And then do furthermore things based on these conditions. It would look something like:
#IBAction func favour(sender: AnyObject) {
if liketext.text == "Like"{
liketext.setTitle("Unlike", forState: UIControlState.Normal)
makeQuoteFavourite()
} else if liketext.text == "Unlike" {
liketext.setTitle("Like", forState: UIControlState.Normal)
}
}
However as many of you know, a button outlet cannot have the .text function. #IBOutlet var liketext: UIButton! How would I be able to compare button strings to normal strings? Are there other possible solutions?
UIButtons simply work differently than UILabels. They have control states for one thing. And their (title) text can be set on a per-control-state basis.
So you have to use the currentTitle property:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIButton_Class/#//apple_ref/occ/instp/UIButton/currentTitle
or the titleForState method:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIButton_Class/#//apple_ref/occ/instm/UIButton/titleForState:
Now those titles are normal String objects; it's the name of the property that's different.

How to have multiple position state for viewcontroller's views?

The problem I'm trying to solve is this: I have a DetailViewController that displays the data for my Model with UIImageView's, UITextFields's, etc.
If the user taps a button, those DetailViewController's views move to different positions and start to be editable. When editable, if the user taps one of the UITextField (just one of them is special) the UITextField moves to the top of the screen and a UITableView appears to autocomplete it (just like when you type something on google).
The user can also tap the same button to go back to the display state (where nothing is editable).
So basically I have some views in a ViewController with 3 possible state: DisplayState, EditingState, EditingWithFocusOnSpecialTextFieldsState.
I'd like to have all those positioning state described by NSLayoutConstraints, and, if possible, just in the storyboard.
One thing I could do is this Animate to a storyboard state / position, but this involves writing every constraint for each state in code, therefore I couldn't visualize them really well in storyboard while developing (Also, writing constraints in code is a lot less maintainable than in storyboard).
What I would like is something like creating 3 different XIBs, for example, or different copies of my DetailViewController in storyboard with the 3 different positions for each of the subviews, and then animate between them.
If it makes any difference, I'm always using the latest iOS version (iOS 8 right now) and Swift.
I do know Objective-C very well too if you don't want to answer in Swift.
As far as I know, there's no way to do this with 3 different views, and get the result you want (at least no straight forward way). One approach would be to make 3 constraints (one for each state) to any one edge of the superview that you need to adjust for each view (in addition to any other constraints you need that you're not going to modify). One would have a high priority (I'm using 900, it can't be 1000), and the other 2 would have a lower priority (499 in my example). When you switch states, you change which of the 3 has the high priority. This does involve making a lot of constraints, and I found that the easiest way to implement the switching in code was to give the constraints identifiers in IB (which you do in the "User Defined Runtime Attributes" section of the Identity Inspector). This approach means I don't have to make IBOutlets for all those constraints. Here is an example with two views in the storyboard,
You can see the text field has 3 constraints to the top, and the image view has 3 centerY constraints (though you can't see that there are 3). Each constraint (in the groups of 3) has its identifier set to "display", "edit", or "focus". I give the one that's called "display" the priority of 900, and the other 2 get 499 (because I want the view to start in display mode). In this test app, I'm using 3 buttons to change the state, though, of course, you could use other means to accomplish that. Here is the code I use to switch the priorities,
enum EditState: String {
case Display = "display" // these strings are the same as the ones assigned to the identifier property of the constraints in IB (in "user defined runtime attributes")
case Editing = "edit"
case EditWithFocus = "focus"
}
class ViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
func updatEditingState(state: EditState) {
var constraintsArray = self.view.constraints() as [NSLayoutConstraint]
constraintsArray += self.imageView.constraints() as [NSLayoutConstraint]
for con in constraintsArray {
if let name = con.identifier? {
if name == "display" || name == "edit" || name == "focus" {
con.priority = (name == state.rawValue) ? 900 : 499
}
}
}
UIView.animateWithDuration(0.5) {self.view.layoutIfNeeded()}
}
#IBAction func EnterEditingState(sender: UIButton) {
updatEditingState(EditState.Editing)
}
#IBAction func enterDisplayStatus(sender: UIButton) {
updatEditingState(EditState.Display)
}
#IBAction func enterFocusStatus(sender: UIButton) {
updatEditingState(EditState.EditWithFocus)
}
}

Resources