这个简单APP是用swfit1.2写的,主要重点是:1.点击键盘return键可退出键盘。 2.各个控件值的传递。
Storyboard界面设计:
View代码:
1 import UIKit 2 3 class ViewController: UIViewController ,UITextFieldDelegate{ 4 5 @IBOutlet weak var name: UITextField! 6 @IBOutlet weak var gender: UISegmentedControl! 7 @IBOutlet weak var birthday: UIDatePicker! 8 @IBOutlet weak var heightNumber: UISlider! 9 @IBOutlet weak var height: UILabel! 10 @IBOutlet weak var hasProperty: UISwitch! 11 @IBOutlet weak var result: UITextView! 12 13 override func viewDidLoad() { 14 super.viewDidLoad() 15 name.delegate = self//点击return退出键盘 16 } 17 override func didReceiveMemoryWarning() { 18 super.didReceiveMemoryWarning() 19 // Dispose of any resources that can be recreated. 20 } 21 22 @IBAction func heightChanged(sender: AnyObject) { 23 var slider = sender as! UISlider 24 var i = Int(slider.value) //Float转换为Int 25 slider.value = Float(i) //转换操作 26 height.text = "(i)厘米" //随着滑块改变label的值 27 } 28 29 @IBAction func okTapped(sender: AnyObject) { 30 let genderText = gender.selectedSegmentIndex==0 ? "高富帅" : "白富美" 31 let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) 32 let now = NSDate() 33 birthday.maximumDate = NSDate()//防止年龄为负数 34 let components = gregorian?.components(NSCalendarUnit.CalendarUnitYear, fromDate: birthday.date, toDate: now, options: NSCalendarOptions(0))//计算年龄 35 36 let age = components!.year//得到年龄 37 let hasPropertyText = hasProperty.on ? "有房":"没房" //switch值的数据 38 39 result.text = "(name.text),(age)岁,(genderText),身高(height.text!),(hasPropertyText),求交往!" 40 41 } 42 43 //UITextFiledDelegate,点击return使键盘退出 44 func textFieldShouldReturn(textField: UITextField) -> Bool{ 45 textField.resignFirstResponder() 46 return true 47 } 48 }
在这代码里需要注意的是,由于swift语言的改变,需要在age和height.text的赋值或显示中在其后加上!,否则会报错。
运行效果:
github地址:https://github.com/AbelSu131/Xiangqin