前言
今天的swift小练习比较简单, 主要目的是如何快速熟悉storyboard拖线后的代码风格. 下面我们来看看运行效果, 通过代码, 我们看看能从中领悟到什么?
-
运行效果
我们再来看看storyboard
- 在来看看代码
import UIKit
import Social
class ViewController: UIViewController {
@IBOutlet weak var nameTextFiled: UITextField!
@IBOutlet weak var genderSegControl: UISegmentedControl!
@IBOutlet weak var salaryLabel: UILabel!
@IBOutlet weak var straightSwitch: UISwitch!
@IBOutlet weak var workTextFiled: UITextField!
@IBOutlet weak var birthdayPicker: UIDatePicker!
@IBAction func salaryHandler(_ sender: Any) {
// 点击这里的要求: 拖动Slider 后面的工资就会改变
let slider = sender as! UISlider
// 获取slider的当前值:
let i = Int(slider.value)
// 赋值
salaryLabel.text = "¥\(i)K"
}
@IBAction func tweetButtonOnClicked(_ sender: Any) {
// 判断几个输入框是否为空, 如果为空, 那么直接返回
if (nameTextFiled.text == "" ||
workTextFiled.text == "" ||
salaryLabel.text == "") {
showAlert("Info Miss", message: "Please fill out the form", buttonTitle: "Ok")
return
}
let name: String! = nameTextFiled.text
let work: String! = workTextFiled.text
let salary: String! = salaryLabel.text
// get age
let gregorian = Calendar(identifier: Calendar.Identifier.gregorian)
let now = Date()
let components = (gregorian as NSCalendar?)?.components(NSCalendar.Unit.year, from: birthdayPicker.date, to: now, options: [])
let age:Int! = components?.year
var interestedIn:String! = "Women"
if (genderSegControl.selectedSegmentIndex == 0 && !straightSwitch.isOn) {
interestedIn = "Men"
}
if (genderSegControl.selectedSegmentIndex == 1 && straightSwitch.isOn ) {
interestedIn = "Women"
}
let tweet = "Hi, I am \(name!). As a \(age!)-year-old \(work!) earning \(salary!)/year, I am interested in \(interestedIn!). Feel free to contact me!"
tweetSLCVC(tweet)
}
fileprivate func tweetSLCVC(_ tweet: String) {
if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeTwitter){
let twitterController:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
twitterController.setInitialText(tweet)
self.present(twitterController, animated: true, completion: nil)
} else {
showAlert("Twitter Unavailable", message: "Please configure your twitter account on device", buttonTitle: "Ok")
}
}
// MARK: - 自定义弹框
fileprivate func showAlert(_ title: String, message: String, buttonTitle: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: buttonTitle, style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
view.endEditing(true)
}
从代码中学到一下几点
1, fileprivate和private的区别: 两者都是关键字, 并且都是修饰私有属性或者私有方法.但是他们之间的区别就是fileprivate修饰的属性或者方法子类是不能访问, 但是private修饰的属性和方法,子类是可以访问的.
2, 如何实现自定义一个简单的弹框
3, 苹果建议我们将多余的代码或者说冗余的代码删除掉, 只需要留下用到的代码即可
4, 注意强制转换的写法, 拼接的写法
总结
不积跬步无以至千里, 不能好高骛远. 代码虽然简单, 任然坚持记录笔记的原因是想养成一个很好的习惯. 不要因简单就忽视它, 也不要因困难而害怕它.