In my app I have got two textfields, one label and one button. I managed to get the content of the one textfield to be displayed in the label, but I want to display the content of both of the textfields.
#IBAction func buttonPushed(sender: UIButton) {
Label.text = "\(textfield1.text)"
+ "\(textfield2.text)"
The code above is the closest I´ve come, but the Label displays:
Optional"whatever I typed in the textfield"Optional"whatever I typed
in the textfield"
You have to unwrap the text
Label.text = textfield1.text! + textfield2.text!
You are concatenating strings, not adding numbers. In order to add the values, you need to cast the textfield value to a number like:
field.text!.toInt()
the ! unwraps the value to remove the "Optional". and toInt() casts a string (text) to and integer.
In the end, you code will look something like this:
#IBAction func buttonPushed(sender: UIButton) {
Label.text = "\(textfield1.text!.toInt())"
+ "\(textfield2.text!.toInt())"
Related
Edit: I figured out how to prevent this, but I still have a question as to why it returns an optional value. You may skip to the end.
I'm quite new to Swift, and I'm getting behavior I can't understand. Let's say I drag a popup button called myButton into the ViewController. I want to print the currently selected item to the console. Here's how I would do it:
#IBOutlet weak var myButton: NSPopUpButton!
override func viewDidLoad() {
super.viewDidLoad()
let myVariable = myButton.titleOfSelectedItem
print(myVariable)
// Do any additional setup after loading the view.
}
I expect Item1 to be printed, as that's the option selected by default when the view loads. However, I actually get Optional("Item 1").
This has been causing a few problems for me. For example, the print(myVariable) line gives me this cryptic error:
Expression explicitly coerced from 'String?' to Any
Also, I can't do something like this:
if myButton.titleOfSelectedItem == "Item1" || "Item3" {
let currentSelection = "odd"
} else {
let currentSelection = "even"
}
as I get a bunch of errors – because of the || and the else as far as I can tell, even though I think it should work fine.
I've tried searching for why this occurs, but couldn't find any explanations. From the warning, it seems like when I get the selection with titleOfSelectedItem, it gives me an optional value. This doesn't make sense, as a menu item has to be selected. Its value can't be nil.
I looked up a bunch of tutorials to see how they implement popup button functionality. The only thing I could see was when someone
Made an array
Removed all items from the popup button with func removeAllItems()
Added items to the popup button from the array with func addItems(withTitles: [String])
Obtained the index of the selected item with var indexOfSelectedItem: Int
Retrieved the respective value from the array
and then used that. This, however, seems unnecessarily complicated and I can't understand why I wouldn't be able to get just the title of the selected popup item simply with myButton.titleOfSelectedItem. Can anyone suggest to me what to do?
Edit:
So I realized you need to "unwrap" the optional value to make it a normal value, which is as simple as adding a ! to the end of the variable, as follows:
#IBOutlet weak var myButton: NSPopUpButton!
override func viewDidLoad() {
super.viewDidLoad()
let myVariable = myButton.titleOfSelectedItem!
print(myVariable)
// Do any additional setup after loading the view.
}
Now there's no error, and Item1 is printed.
What I can't yet understand is, why was an optional value printed in the first place? There are three items in the NSPopUpButton. Any one of the three has to be selected. There's no opportunity for myButton.titleOfSelectedButton to be nil. Why then do I need to unwrap it to use it as a string with myButton.titleOfSelectedButton! if it's not optional?
titleOfSelectedItem returns an optional because no item could be selected.
You need optional bindings to unwrap the optional safely and you have to evaluate both "Item1" and "Item3" against the title string:
if let title = myButton.titleOfSelectedItem {
print(title)
let currentSelection : String
if title == "Item1" || title == "Item3" {
currentSelection = "odd"
} else {
currentSelection = "even"
}
}
In Objective C you can do it in awakeFromNib:
[[your_NSView your_NSPopUpButton] selectItemAtIndex:your_Int];
... of course, you must have declared 'your_NSView' and 'your_NSPopUpButton' as properties.
I am new to swift and been learning how to do it on my own through tutorials. I was able to make the title of a button change when clicked on. I wanted to dynamically change the title of a label. It doesn't necessarily have to be clicked on like a button. This is a label for the NStouchbar.
The code below is how I managed to change the button label. I noticed that labels do not have the .title action so I am not sure how I would go about changing that.
#IBAction func buttonOneTapped(_ sender: Any) {
print("Button One Tapped")
buttonOne.title = "1 BTC = $" + dollar
}
To get the label of a button and edit it do it like this:
button.titleLabel?.text
And just as a suggestion, instead of using the + sign to concatenate a string and a float or double I would do it like this:
"1 BTC = $\(dollar)"
I forgot the name of this method :| but it's the more swifty way. :]
Heys guys,
I am pretty new into programming and therefore I've followed I course on Udemy to teach me Swift 2.2.
For learning purpose I have been trying to program a BMI-calculator where I have a textfield (which just displays the value) and a slider where I can put my weight in kg. After dragging the slider the value is visible in the textfield. I cannot put a value into the textfield so that it is displayed on the slider!
The same textfield-slider relation is used with the height in cm. Now I created an IBAction the bring my kgSlider.value into my kgField.text and it looks like this:
#IBAction func kgSet(sender: AnyObject) {
kgField.text! = String(Int(kgSlider.value))
}
Thats works fine but I unwrapped (like the teacher in the course) without knowing, if there really is a value. Okay, I know in this case that there will be a value, but I would like to go more real and therefore I tried to use an Optional-Binding to find out, if there is a value instead of directly unwrap it.
Therefore I used the cm.Field and the cm.Slider in my code but it doesn't work for now and I don't know why. The code is the following:
#IBAction func cmSet(sender: AnyObject) {
if let tempCm = String(Int(cmSlider.value)) as String! {
cmField.text = tempCm
}
}
So I created the constant called tempCM which will got the value from the cmSlider, if there is a value. Therefore I casted the cmSlider.value like in the other IBAction into an Int and then into a String. If there is the value it will carry it into the cmField.text. This didn't work, therefore I tried to use the "as String!" statement but know I get always 0 instead of the correct value.
So what am I doing wrong there?
So, this should compile fine and provide you with your desired result.
#IBAction func cmSet(sender: AnyObject) {
if let tempCm = String(Int(cmSlider.value)) {
cmField.text = tempCm
}
}
You could also try this
cmField.text = String(Int(cmSlider.value)) ?? " "
in the second example, you are using the optional operator to say if you can convert this to an Int then that Int to a string set the cmField.text property to its value, otherwise use a blank space as the default value.
I Am trying to build a very simple app:
It will print elements of an array so here are my two questions
in my current code
#IBOutlet weak var moussarLabel: UILabel!
#IBAction func moussarButton(sender: AnyObject) {
var moussar = ["dzv","avazv","sdv dv","dvar3"]
for var i = 0; i<moussar.count; i++ {
moussarLabel.text = "\(moussar[i])"
}
}
I want to know two things:
when the code executes it automatically print the last element of the array without displaying the other elements
Say that I want the text in the array to be much much longer, how do i make UILabel to adapt to the text and to allow the user to scroll though the text?
thanks for the help
The final element in the array is the last thing the loop assigns to the text label. Sounds like its working as expected. Did you mean to concatenate (add) the strings?
You can do that with a UITextView https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextView_Class/
First of all, you can't scroll a UILabel so you'll have to use a UITextField. Read the documentation for details, it shouldn't be too hard when only displaying a single word. For getting the last element of the array, use moussarLabel.last which returns an optional. As the text property of a text view or a label, respectively, accepts nil as value, this isn't a problem.
You should make the array scoped to the class and not the function. In addition a counter variable can be used to access different elements.
To make the text scrollable you can use a UITextView:
#IBOutlet weak var moussarLabel: UITextView!
var moussar = ["dzv","avazv","sdv dv","dvar3"]
var moussarIndex = 0
#IBAction func moussarButton(sender: AnyObject) {
moussarLabel.text = "\(moussar[moussarIndex++])"
// if you want to cycle through the array use the following condition
if moussarIndex >= moussar.count {
moussarIndex = 0
}
}
I want to get the length of the text that is entered in a UISearchBar
I use the function that is called when the the searcbbar text starts editing.
func searchBarTextDidBeginEditing(searchBar: UISearchBar!) {
println("EDITING")
//TODO: Get length of text entered in searchBar
}
This doesn't work:
func searchBarTextDidBeginEditing(searchBar: UISearchBar!) {
println("EDITING")
//TODO: Get length of text entered in searchBar
//Doesn't work. Error: String doesn't have a member named length
searchBar.text.length
}
How can i retrieve the length of the entered text?
Ended up doing this:
searchBar.text.bridgeToObjectiveC().length
The problem is simply that the text property, like most objects arriving from the Cocoa API, might be nil. You have to assure Swift that it is not. Like this:
let len = countElements(searchBar.text!)