How can I get the selected value of a UIPickerViewControl in Swift?
I tried something like this:
labelTest.text = Spinner1.selectedRowInComponent(0).description
But this only returns the selected index. I need the value.
Anyone who knows how to do this?
you will have to set the picker view delegate to self and override this function
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
// use the row to get the selected row from the picker view
// using the row extract the value from your datasource (array[row])
}
or
you can use this to extract as per your usage
var selectedValue = pickerViewContent[pickerView.selectedRowInComponent(0)]
where pickerViewContent is your array of dataSource
Swift 3: supose you want the String value of each row selected
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let valueSelected = yourDataSourceArray[row] as String
}
Swift 4
let selectedYearPicker = pickerData[yearPicker.selectedRow(inComponent:
print(selectedYearPicker)
Or
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let yearValueSelected = pickerData[row] as String
print(yearValueSelected)
}
All the answers so far presuppose you can easily connect the selected row back to the original data array. The solution is fairly easy if you can do that, but the question specifically addresses the case where the original array is not readily available. For instance I have 3 pickers in table cells that expand when one row is tapped, and they show 3 different arrays.
It would save me a lot of trouble if I could simply retrieve the selected text from the picker itself, perhaps in the code for my custom cell, instead of having to figure out which picker, which data array, which row and so on.
If the answer is that you can't, that's OK, I'll sort it all out. But the question is whether there's a shortcut.
The accepted answer is right except for it should include a typecast from String to Int:
var selectedValue = pickerViewContent[Int(pickerView.selectedRowInComponent(0))!]
Related
I want to Field sort based on multiple fields. I have a slice of elastic.FieldSort (say, sorter) and I want to do something like:
searchSource := elastic.NewSearchSource()
// searchSource.SortBy(sorter...) // Unpacking of slice isn't working
I know that this SortBy accepts single elements as:
searchSource.SortBy(sorter[0], sorter[1], sorter[2])
but the issue is that I have a slice of dynamic size. Please help me how this can be implemented, or is there any better to do this?
The slice unpack would work if the type is right.
package main
import (
"fmt"
)
func print(data ...string) {
fmt.Println(data)
}
func main() {
d := []string{"hello", "world", "now"}
print(d...)
}
For this specific example how if for any reason the unpack is not working still, there is a work around to this.
Since the SortBy function just appends to the underlying sorters slice https://github.com/olivere/elastic/blob/v7.0.22/search_source.go#L160
func (s *SearchSource) SortBy(sorter ...Sorter) *SearchSource {
s.sorters = append(s.sorters, sorter...)
return s
}
You can do
for _, sorter := range sorters {
searchSource.SortBy(sorter)
}
I figured out the issue. There were two problems with my code.
First, I needed to initialize the slice (sorter) as type Sorter:
var sorter []elastic.Sorter
Second issue was on Elastic side. I needed to pass suffix keyword with keyword type fields like,
var fieldName string = field.FieldName
if field.Keyword {
fieldName = field.FieldName + ".keyword"
}
And then use this fieldName to create NewFieldSort. This is why I was getting elastic error 404.
sorter = append(sorter, elastic.NewFieldSort(fieldName).Order(true)
Rest of the code was same, I was passing the sorter slice to the sortBy method:
searchSource.SortBy(sorter...)
I'm new to Go and I'm trying to learn it by making a repost bot. Anyway, I'm having a problem that I don't know how to solve exactly.
I have the following Struct:
type Post struct {
Title string
Url string
}
And I'm trying to get these values using goQuery, like this:
var title = doc.Find(".title.title.may-blank").Each(func(i int, s *goquery.Selection) {
fmt.Println("Title:", s.Text())
})
But when I try to set the value to the Post struct, I get this error:
cannot use title (type *goQuery.Selection) as type string in field value.
Ok, that makes sense, but how can I cast it to string? I've tried s.Text() but it doesn't works. I thought about making a function that returns a string, but I'm not sure if this would work.
I'll appreciate if someone can help me, thanks in advance!
The issue is that .Each returns the original *goquery.Selection so that you can chain calls. If you need to get the string value, you just assign it directly, like this:
var title string
doc.Find(".title.title.may-blank").Each(func(i int, s *goquery.Selection) {
title = s.Text()
})
I have a slider and I want to limit its value to range from 1 to 5. I have set the min and max values on both Interface Builder and in codes but am currently facing two main issues.
1) The value doesn't change (keeps saying value 1).
2) On top of that, I am also unable to adjust the value of the slider when VoiceOver accessibility mode is on. The value keeps reading it as 1, even though on the surface, it may be on value 3/4/5.
Here are some of my codes to implement the slider in Swift. I am not sure what is the problem here with this. Any help is appreciated!
#IBOutlet weak var busSlider: UISlider!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
busSlider.minimumValue = 1
busSlider.maximumValue = 5
}
override func viewDidAppear(animated: Bool) {
busSlider.accessibilityValue = NSNumberFormatter.localizedStringFromNumber(busSlider.value, numberStyle: NSNumberFormatterStyle.DecimalStyle)
busSlider.accessibilityLabel = NSLocalizedString("\(Int(busSlider.value))", comment: "")
}
override func accessibilityIncrement() {
busSlider.value++
busSlider.sendActionsForControlEvents(UIControlEvents.ValueChanged)
busSlider.accessibilityValue = NSNumberFormatter.localizedStringFromNumber(busSlider.value, numberStyle: NSNumberFormatterStyle.DecimalStyle)
busSlider.accessibilityLabel = NSLocalizedString("\(Int(busSlider.value))", comment: "")
}
override func accessibilityDecrement() {
busSlider.value--
busSlider.sendActionsForControlEvents(UIControlEvents.ValueChanged)
busSlider.accessibilityValue = NSNumberFormatter.localizedStringFromNumber(busSlider.value, numberStyle: NSNumberFormatterStyle.DecimalStyle)
busSlider.accessibilityLabel = NSLocalizedString("\(Int(busSlider.value))", comment: "")
}
*On the side note: I actually have 2 sliders on the same screen but belonging to different sections. The first slider reads the value in percentage (speak rate), and this slider needs to read the value in integer (number of stops).
In the implementation of theNSTableViewDataSource method
func tableView(tableView: NSTableView!, objectValueForTableColumn tableColumn: NSTableColumn!, row: Int) -> AnyObject!
, the returned result for a column is a native Swift Bool-typed value. I expected it being displayed as true or false in the table view. However, it is actually displayed as 1 or 0. I guess it might have been casted to AnyObject and became an Obj-C object. What's an easy way to make them displayed as true or false in the table view?
The Objective-C Bool type is actually an signed char under the covers.
objc.h:typedef signed char BOOL;
objc.h:#define YES ((BOOL)1)
objc.h:#define NO ((BOOL)0)
So when you return this as an object, you're actually returning something that gets cast to an NSInteger, which is why it's showing a 0 or 1.
To solve this, modify your object method to return
return theBoolValue ? #"true" : #"false"
In Apple's "A swift Tour" they have this code snippet:
enum OptionalValue<T> {
case None
case Some(T)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some(100)
How would you get the 100? You can't do possibleInteger == 100 to test if possibleInteger has the value 100 inside. I know you can put functions inside enumerations, but you can't have variables. Maybe I'm understanding enumerations wrong…
If I command click Optional when declaring an optional (var x:Optional<Int>), I can find
enum Optional<T> : Reflectable, NilLiteralConvertible {
case None
case Some(T)
init()
init(_ some: T)
/// Haskell's fmap, which was mis-named
func map<U>(f: (T) -> U) -> U?
func getMirror() -> MirrorType
static func convertFromNilLiteral() -> T?
}
But I do not understand what any of that means. Help?
You can use a switch statement to get the value, as described here. Relevant bit:
... the associated values can be extracted as part of the switch
statement. You extract each associated value as a constant (with the
let prefix) or a variable (with the var prefix) for use within the
switch case’s body:
For your case, you'd want something like:
switch possibleInteger {
case .Some(let value):
println(value)
case .None:
println("<None>")
}