继续此系列上一篇文章的项目
本篇要实现一个简单的小应用, 通过点击一个按钮, 随机生成一串字符串.
在MainWindowController.xib创建控件
在MainWindowController.swift中创建@IBOutlet
import Cocoa
class MainWindowController: NSWindowController {
//创建IBOutlet, 一会用于在xib面板中绑定控件
@IBOutlet weak var textFiled:NSTextField!
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
}
在xib面板中绑定@IBOutlet
如图, 在File's Owner点击右键, 在Outlets中选择之前创建的textFiled, 左键点击右边的空圈, 拖拉到面板中的NSTextField控件上, 进行绑定
在MainWindowController.swift中创建@IBAction
如代码注释2, 添加@IBAction
import Cocoa
class MainWindowController: NSWindowController {
//1. 创建IBOutlet, 一会用于在xib面板中绑定控件
@IBOutlet weak var textFiled:NSTextField!
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
//2. 创建IBAction, 一会用于在xib面板中给button绑定事件
@IBAction func MyButtonClick(sender: AnyObject) {
textFiled.stringValue = "my button clicked"
}
}
回到Xib中绑定@IBAction
如图, File's Owner右键, Received Actions栏目中多了一个刚刚在代码中创建的MyButtonClick, 点击右边的空心圈, 拖拉到需要绑定的按钮上
绑定成功之后, 运行代码
如图, 点击按钮, 他会执行@IBAction的MyButtonClick方法
新建GeneratePassword.swift文件
给GeneratePassword实现随机字符串的方法
import Foundation
private let chars = Array(arrayLiteral: "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e",
"f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
"V", "W", "X", "Y", "Z")
func generateRandomString(length: Int) -> String {
var string = ""
for _ in 0..<length {
string.append(generateRandomCharacter())
}
return string
}
func generateRandomCharacter() -> Character {
let length = UInt32(chars.count)
let index = Int(arc4random() % length)
let character = Character(chars[index])
return character
}
替换原先的MyButtonClick方法
import Cocoa
class MainWindowController: NSWindowController {
//1. 创建IBOutlet, 一会用于在xib面板中绑定控件
@IBOutlet weak var textFiled:NSTextField!
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
//2. 创建IBAction, 一会用于在xib面板中给button绑定事件
@IBAction func MyButtonClick(sender: AnyObject) {
// textFiled.stringValue = "Hello IBAction"
//3. 替换原先得Hello IBAction字符
let password = generateRandomString(12)
textFiled.stringValue = password
}
}