以下是该应用的主屏幕:
我已经成功地将这些pickerView相互链接,然后我尝试在转换时分配计算,但没有效果:
ex:mile to killo 但我找不到办法这样做。我曾试图使用" Switch"仍然没有发生。我只需要有人可以告诉我如何通过textFields从某个单元转换到另一个单元。例如,如果在某个texField中输入值,则转换后的结果将在另一个textField中,反之亦然。
这是我的代码:
import UIKit
类ViewController:UIViewController,UIPickerViewDataSource,UIPickerViewDelegate,UITextFieldDelegate {
@IBOutlet weak var mainPicker: UIPickerView!
@IBOutlet weak var leftPicker: UIPickerView!
@IBOutlet weak var rightPicker: UIPickerView!
@IBOutlet weak var textFieldLeft: UITextField!
@IBOutlet weak var textFielfRight: UITextField!
@IBOutlet weak var equal: UILabel!
var leftPickerData : [String] = []
var rightPickerData : [String] = []
var dataDict:NSMutableDictionary!
var mainPickerData:NSArray!
var leftRightPickerData:NSArray!
//yourPicker.backgroundColor = UIColor(patternImage: UIImage(named: "back.jpg")!)
override func viewDidLoad() {
super.viewDidLoad()
mainPicker.backgroundColor = .clear
rightPicker.backgroundColor = .clear
leftPicker.backgroundColor = .clear
// Connect data to ViewController ..
self.mainPicker.delegate = self
self.mainPicker.dataSource = self
self.leftPicker.delegate = self
self.leftPicker.dataSource = self
self.rightPicker.delegate = self
self.rightPicker.dataSource = self
self.textFieldLeft.delegate = self
self.textFielfRight.delegate = self
let theWidth = view.frame.size.width
let theHeight = view.frame.size.height
mainPicker.center = CGPoint(x: theWidth/2, y: theHeight/2 - 182.5)
leftPicker.center = CGPoint(x: theWidth/2 - 100, y: theHeight/2)
rightPicker.center = CGPoint(x: theWidth/2 + 100, y: theHeight/2)
textFieldLeft.center = CGPoint(x: theWidth/2 - 90, y: theHeight/2 + 110)
textFielfRight.center = CGPoint(x: theWidth/2 + 90, y: theHeight/2 + 110)
equal.center = CGPoint(x: theWidth/2, y: theHeight/2 + 110)
dataDict = ["Area":["Square Mile", "Square Yard", "Square Foot", "Square Inch", "Hectare", "Acre", "Square Kilometer", "Square Meter", "Square Centimeter", " Square Millimeter"]
,"Energy":["Btus", "Calories", "Ergs", "Foot-Pounds", "Joules", "Kilogram-Calories", "Kilogram-Meters", "Kilowatt-Hours", "Newton-Meters", "Watt-Hours"], "Length":["Mile", "Yard", "Foot", "Inch", "Kilometer", "Meter", "Centimeter", "Millimeter"], "Power": ["Btus/Minute", "Foot-Pounds/Min", "Foot-Pounds/Sec", "Horsepower", "Kilowatts", "Watts"], "Pressure": ["Pounds/Sqr Ft", "Pounds/Sqr In", "Atmospheres", "Bars", "In of Mercury", "Cm of Mercury", "Kilograms/Sqr Meter", "Pascals"], "Speed": ["Knots", "Miles/Hr", "Miles/Min", "Feet/Min", "Feet/Sec", "Kilometers/Hr", "Kilometer/Min", "Meters/Sec"], "Temperature": ["Celsius C˚", "Fahrenheit", "Kelvin"], "Time": ["Years", "Months", "Weeks", "Days", "Hours", "Minutes", "Seconds", "Millisconds", "Microseconds", " Nanoseconds"], "Volume": ["Cupic Feet","Cubic Meter", "Gallon (Imp)", "Gallon (US)", "Quart (US)", "Pint (US)", "Fluid Oz", "Cup", "Tablespoon", "Teaspoon", "Dram (US)", "Liter"], "Weight": ["Short Ton (US)","Long Ton (UK)", "Pound (U.S)", "Ounce (US)", "Stone", "Metric Ton", "Kilogram", "Gram"]]
mainPickerData = dataDict.allKeys as NSArray!;
leftRightPickerData = dataDict.object(forKey: mainPickerData.firstObject as! String) as! NSArray
// Linking the textFields with the pickerViews.
//textFieldLeft.inputView = leftPicker;
// textFielfRight.inputView = rightPicker;
}
// The number of columns of data
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
// The number of rows of data
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch (pickerView.tag) {
case mainPicker.tag:
return mainPickerData.count
case leftPicker.tag,rightPicker.tag:
let currentSelectedIndex = mainPicker.selectedRow(inComponent: component)
leftRightPickerData = (dataDict.object(forKey: mainPickerData[currentSelectedIndex] as! String) as! NSArray)
return leftRightPickerData.count;
default:
break;
}
return 0;
}
// The data to return for the row and component (column) that's being passed in
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if leftPicker.tag == 2 {
return leftPickerData[row]
}else if rightPicker.tag == 3{
return rightPickerData[row]
}
return ""
}
// Catpure the picker view selection
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// This method is triggered whenever the user makes a change to the picker selection.
// The parameter named row and component represents what was selected.
if(pickerView.tag == 1 ){
let currentSelectedIndex = mainPicker.selectedRow(inComponent: component)
leftRightPickerData = (dataDict.object(forKey: mainPickerData[currentSelectedIndex] as! String) as! NSArray)
leftPicker.reloadAllComponents()
rightPicker.reloadAllComponents()
if mainPicker.tag == mainPicker.selectedRow(inComponent: component) {
if leftPicker.tag == leftPicker.selectedRow(inComponent: component) && rightPicker.tag == rightPicker.selectedRow(inComponent: component){
textFieldLeft.text = textFielfRight.text
}
}
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textFieldLeft.resignFirstResponder()
textFielfRight.resignFirstResponder()
return true
}
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let titleData : String?
if(pickerView.tag == mainPicker.tag){
titleData = mainPickerData[row] as? String;
}
else{
let currentSelectedIndex = mainPicker.selectedRow(inComponent: 0)
leftRightPickerData = (dataDict.object(forKey: mainPickerData[currentSelectedIndex] as! String) as! NSArray)
titleData = leftRightPickerData[row] as? String;
}
let myTitle = NSAttributedString(string: titleData!, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 12.0)!,NSForegroundColorAttributeName:UIColor.blue])
return myTitle;
}
}
答案 0 :(得分:1)
我会做这样的事情作为不同长度值的例子:
您可能希望存储某种跟踪每个不同测量单位的转换值的数组,最佳通用长度单位为米。确保每个单元的相应值保持静态是个好主意,因此创建一个enum
:
enum Length: Int {
case mile = 0
case yard = 1
case foot = 2
case inch = 3
case kilometer = 4
// ... keep going with all lenght units of measurement
}
然后你应该为转换创建一个值数组,这是一个双精度数组,基于我在上面enum
中列出的转换为meters
的长度值:
// Store values with corresponding indicies in array to the Length enum's values
let meterConversions:[Double] = [1609.34, 0.9144, 0.3048, 0.0254, 1,000]
// Store values of length unit descriptions to print after conversion in TextField, long hand or short hand whatever you prefer. (this is optional)
let lengthUnits = ["Mile", "Yard", "Foot", "Inch", "Kilometer"]
然后创建一些转换方法:
// Convert length type to meters
func convertToMeters(type: Length, unitValue: Double) -> Double {
return (meterConversions[type.rawValue] * unitValue)
}
// Convert meters back to length type
func convertFromMeters(type: Length, meterValue: Double) -> Double {
return meterValue/meterConversions[type.rawValue]
}
// Convert from length type to other length type
func convertType(from: Length, to: Length, unitValue: Double) -> Double {
// Convert from value to meters to start
let fromValueToMeters:Double = convertToMeters(type: from, unitValue: unitValue)
// Now use that value to convert back to desired unit
let newUnitValue:Double = convertFromMeters(type: to, meterValue: fromValueToMeters)
return newUnitValue
}
然后,当用户在左侧或右侧UIPickerView
中选择新行时,更新计算并按照您的意愿处理它:
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// Make sure there is actually some text in the left text field, otherwise return
guard let text = textFieldLeft.text else { print("textFieldLeft doesn't contain any text"); return }
// You are going to need a numerical (Double) value from the user's text
let stringAsDouble = Double(text)
// Now check that the text was actually a numerical value able to be converted to a double
if let value = stringAsDouble {
var typeA:Length!
var typeB:Length!
if pickerView == leftPicker {
typeA = Length(rawValue: row)!
typeB = Length(rawValue: rightPicker.selectedRow(inComponent: 0))!
converted = convertType(from: typeA, to: typeB, unitValue: value)
}
else if pickerView == rightPicker {
typeA = Length(rawValue: leftPicker.selectedRow(inComponent: 0))!
typeB = Length(rawValue: row)!
let value:Double = 0 // Determine user entered value from textField
converted = convertType(from: typeA, to: typeB, unitValue: value)
}
updateValueAfterConversion(originalValue: value, originalType: typeA, convertedValue: converted, convertedType: typeB)
} else {
print("Couldn't convert text to double value")
}
}
func updateValueAfterConversion(originalValue: Double, originalType: Length, convertedValue: Double, convertedType: Length) {
// Update text in both fields, lengthUnits part is optional if you want to print unit along with value.
// Update text on left side
textFieldLeft.text = "\(originalValue) \(lengthUnits[originalType.rawValue])"
// Update text on right side
textFieldRight.text = "\(convertedValue) \(lengthUnits[convertedType.rawValue])"
}
答案 1 :(得分:0)
我会给你一些提示:
如果您是一名懒惰的开发人员,我会为您找到这个:https://github.com/michalkonturek/MKUnits
希望这有帮助。