快速使用UIPickerView和多个组件 [英] Using UIPickerView with multiple components in swift
问题描述
您好,我一直在尝试使这个装置工作多年,但没有成功,所以如果你们觉得这很容易,我深表歉意。
Hi there I have been trying to get this working for ages with no success so apologies if this seems easy for you guys.
我想使用3轮UIPickerView-第一个转轮的didSelectRow值将用于更改其余两个转轮的数组,但它们与转换应用程序相同。
I want to use a 3 wheel UIPickerView - The 1st wheel didSelectRow value will be used to change the array for the remaining two wheels but they will be the same as it is a conversion app.
在安装轮子时说我Anyobject与String不相同时抛出一个错误。我看不到任何错误,但我知道这是我错过的基本知识。
It seems to throw me an error up when populating the wheels saying that Anyobject is not identical to String. I cannot see anything wrong but I know it is something basic I have missed.
任何指针都将不胜感激。
Any pointers would be much appreciated.
Motty。
// ViewController.swift
// picker test
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate {
@IBOutlet weak var picker1Label: UILabel!
@IBOutlet weak var picker2Label: UILabel!
@IBOutlet weak var bigPicker: UIPickerView!
var wheelContents = []
var length = ["metres","feet","yards","inches","mm","cm","miles"]
var volume = ["m3","US Gall","Imp Gall","Barrels", "cubic FT","litres"]
var conType = ["length","volume"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
wheelContents = [conType,length,length]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//For main selection of type of conversion
// returns the number of 'columns' to display.
func numberOfComponentsInPickerView(bigPicker: UIPickerView) -> Int{
return wheelContents.count
}
// returns the # of rows in each component..
func pickerView(bigPicker: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
return wheelContents[component].count
}
func pickerView(bigPicker: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!{
return wheelContents[component][row]
}
}
推荐答案
因为您这样声明wheelContents wheelContents = []
,但未指定其元素类型,编译器会自动推断它是AnyObjects的数组,又名 [AnyObject]
。
Since you declared wheelContents like this wheelContents = []
, without specifying its elements type, the compiler automatically infers that it is array of AnyObjects aka [AnyObject]
.
这就是为什么您返回 wheelContents [component] .count
会生成错误:那时编译器期望的是 String!
但您提供的是 AnyObject
。
That's the reason why when you are returning wheelContents[component].count
it generates an error: at that moment the compiler is expecting a String!
but you are providing an AnyObject
.
这是一个非常简单的解决方法,您只需指定声明时将是数组。 (它是一个字符串数组,又称为 [[String]]
)
It's a really easy fix, you should just specify what the content of the array it is going to be when you declare it. (it's an array of arrays of strings aka [[String]]
)
这篇关于快速使用UIPickerView和多个组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!