我正在尝试创建一个快速测试系统来制作数组并显示它。文本输入到文本字段中,当按下按钮时,文本被添加到数组中,并且输出文本被更新。但是,如果我想将数据“Sandwich”添加到数组中,它会在标签中输出'Optional(“Sandwich”)'。我已经尝试过用了?而且!把它拿出来,但似乎没有任何效果。有谁知道如何解决这个问题?
@IBOutlet weak var dataEntryTextField: UITextField!
@IBOutlet weak var addDataButton: UIButton!
@IBOutlet weak var addDataLabel: UILabel!
@IBOutlet weak var dataOutput: UILabel!
var List = [""]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.dataEntryTextField.text = ""
self.dataOutput.text = ""
dataOutput.sizeToFit()
//Add more attributes here
//Apply to the label
dataOutput.backgroundColor = UIColor.grayColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(TextField: UITextField) -> Bool
{
dataEntryTextField.resignFirstResponder()
return true;
}
@IBAction func addData(sender: UIButton) {
if self.dataEntryTextField.text == "" {}
else {
if List == [""] {List[0] = "• \(self.dataEntryTextField.text)"}
else {List.append("• \(self.dataEntryTextField.text)")}
self.dataOutput.text = List.joinWithSeparator(" ")
}
self.dataEntryTextField.text = ""
dataEntryTextField.resignFirstResponder()
}
答案 0 :(得分:0)
您必须使用可选绑定来打开可选值。假设您有一个可选文本
var text: String? = "Sandwich"
print("\(text)") // This would print "Optional("Sandwich")"
当使用可选绑定解包时,您将获得实际文本,但值不是nil。
if let unwrappedText = text {
print("\(unwrappedText)") // This will print "Sandwich"
}
请参阅此link以了解Optionals。
在您的代码中,您必须打开self.dataEntryTextField.text
值并将其附加到列表中。