一.使用Text Field
text field可以接受字符串和数字,可以通过下面的属性来获取值:
- intValue:如果是字符串,则为0,如果浮点数,则去掉小数部分
- floatValue或doubleValue:如果是字符串,则为0.0
- stringValue:
除了标准的text field,Xcode也提供其它几种:
- Text Field with Number Formatter
- Secure Text Field
- Search Field
- Token Field
二.使用Combo Box
一个combo box基于NSComboBox类,可以展示一系列选项,并且允许用户进行输入。有两种方式来填充它的pop-up选项列表:使用属性检查面板或者外部的数据源(data source)
1.使用属性检查面板
代码如下:
AppDelegate.swift文件
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var myCombo: NSComboBox!
@IBOutlet weak var comboResult: NSTextField!
func applicationDidFinishLaunching(aNotification: NSNotification) {
}
func applicationWillTerminate(aNotification: NSNotification) {
}
@IBAction func showResult(sender: AnyObject) {
comboResult.stringValue=myCombo.stringValue
}
}
2.外部的数据源(data source)
当combo box需要展示会改变的数据时,数据源是最好的,你需要实现NSComboBoxDataSource协议:
示例代码为:
AppDelegate.swift文件
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate,NSComboBoxDataSource {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var myCombo: NSComboBox!
@IBOutlet weak var comboResult: NSTextField!
let myArray=["中国","美国","俄罗斯","德国"]
func applicationDidFinishLaunching(aNotification: NSNotification) {
myCombo.usesDataSource=true
myCombo.dataSource=self
numberOfItemsInComboBox(myCombo)
comboBox(myCombo, objectValueForItemAtIndex: 0)
}
func numberOfItemsInComboBox(aComboBox: NSComboBox) -> Int {
return myArray.count
}
func comboBox(aComboBox: NSComboBox, objectValueForItemAtIndex index: Int) -> AnyObject {
return myArray[index]
}
func applicationWillTerminate(aNotification: NSNotification) {
}
@IBAction func showResult(sender: AnyObject) {
comboResult.stringValue=myCombo.stringValue
}
}
效果如图: