Swift学习之路

Swift出来已经有3年多了,在最近的一次计算机语言排行中,swift已经杀入了前十行列。作为一位iOS开发者,迟迟没有入手swift确实说不过去(这里不谈工作),但我一直相信,学习这种事就跟种树一样,在两种时候最好,一种是十年前,另一种则是现在。所以,在这里记录一下自学过程中觉得重要的。

1.忽略参数标签

如果你不希望为某个参数添加一个标签,可以使用一个下划线( _ )来代替一个明确的参数标签。

func someFunction(_ firstParameterName: Int, secondParameterName: Int) {
// 在函数体内,firstParameterName 和 secondParameterName 代表参数中的第一个和第二个参数值
}
someFunction(1, secondParameterName: 2)

2.默认参数值

你可以在函数体中通过给参数赋值来为任意一个参数定义默认值。当默认值被定义后,调用这 个函数时可以忽略这个参数

func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {
// 如果你在调用时候不传第二个参数,parameterWithDefault 会值为 12 传入到函数体中。
 }
 someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6) // parameterWithDefault = 6
 someFunction(parameterWithoutDefault: 4) // parameterWithDefault = 12

将不带有默认值的参数放在函数参数列表的最前。一般来说,没有默认值的参数更加的重要,将不带默认值的参
数放在最前保证在函数调用时,非默认参数的顺序是一致的,同时也使得相同的函数在不同情况下调用时显得更
为清晰。

3.可变参数

一个可变参数可以接受零个或多个值。函数调用时,你可以用可变参数来指定函数参数 可以被传入不确定数量的输入值。通过在变量类型名后面加入( ... )的方式来定义可变参数。

func arithmeticMean(_ numbers: Double...) -> Double {
     var total: Double = 0
     for number in numbers {
         total += number
     }
     return total / Double(numbers.count)
 }
arithmeticMean(1, 2, 3, 4, 5)
// 返回 3.0, 是这 5 个数的平均数。 arithmeticMean(3, 8.25, 18.75)
// 返回 10.0, 是这 3 个数的平均数。

一个函数最多只能拥有一个可变参数

4.在实例方法中修改值类型

结构体和枚举是值类型。默认情况下,值类型的属性不能在它的实例方法中被修改。但是,如果你确实需要在某个特定的方法中修改结构体或者枚举的属性,你可以为这个方法选择 可变(mutatin g) 行为,然后就可以从其方法内部改变它的属性;并且这个方法做的任何改变都会在方法执行结束时写回到原始 结构中。
要使用可变方法,将关键字mutating 放到方法的func关键字之前就可以了:

struct Point {
     var x = 0.0, y = 0.0
     mutating func moveByX(deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY }
}
var somePoint = Point(x: 1.0, y: 1.0)
somePoint.moveByX(2.0, y: 3.0)
print("The point is now at (\(somePoint.x), \(somePoint.y))") // 打印 "The point is now at (3.0, 4.0)"

5.UIButton的使用方法

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let button:UIButton = UIButton(type:.system)
        button.frame = CGRect(x:100,y:100,width:70,height:70)
        button.setTitle("杰哥开始学习swift了", for:.normal)
        button.setTitleColor(UIColor.green, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
       // button.backgroundColor = UIColor.yellow
        let iconImage = UIImage(named:"grzx_gd_body_icon_appstorepf@2x")?.withRenderingMode(.alwaysOriginal)
        button.setImage(iconImage, for: .normal)
        //添加点击方法,方法是并存的
        button.addTarget(self, action:#selector(tapped), for: .touchUpInside)
        button.addTarget(self, action: #selector(ttt(_:)), for: .touchUpInside)
        button.titleLabel?.lineBreakMode = .byTruncatingHead//省略文字开头,.byClipping直接将多余的截取掉,byWordWrapping自动换行
        //当设置自动换行后(byWordWrapping 或 byCharWrapping),我们可以在设置 title 时通过 \n 进行手动换行
        button.titleLabel?.lineBreakMode = .byWordWrapping
        button.setTitle("杰哥开始\n学习swift了", for: .normal)
        self.view.addSubview(button)
    }
    
    func tapped()  {
        print("杰哥!!!")
    }
    func ttt(_ jige:UIButton) {
        print("jieii")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

6.AlertViewController弹出框

func AlertVC() {
        let alertVC = UIAlertController(title:"是否弹出", message:"提示框",preferredStyle:.alert)//actionSheet
        let alertaction = UIAlertAction(title:"cancel",style:.cancel,handler:nil)
        let alertOK = UIAlertAction(title:"ok",style:.destructive,handler:{
            action in
            print("okokokok")
        })
        alertVC.addAction(alertOK)
        alertVC.addAction(alertaction)
        self.present(alertVC,animated: true)
        
    }

弹出框弹出1.5s后隐藏

let alertController = UIAlertController(title: "保存成功!",
                                                message: nil, preferredStyle: .alert)
        //显示提示框
        self.present(alertController, animated: true, completion: nil)
        //两秒钟后自动消失
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5) {
            self.presentedViewController?.dismiss(animated: false, completion: nil)
        }

添加textfield

alertController.addTextField {
            (textField: UITextField!) -> Void in
            textField.placeholder = "用户名"
        }
alertController.addTextField {
            (textField: UITextField!) -> Void in
            textField.placeholder = "密码"
            textField.isSecureTextEntry = true
        }

7.UILabel使用

    func labelLizi() {
      let label = UILabel(frame: CGRect(x: 60, y: 60, width: 100, height: 20))
      label.text = "杰杰杰杰dfsagdgadslgjsdl;g"
        label.textColor = UIColor.green
        label.font = UIFont.systemFont(ofSize: 12)
        label.textAlignment = .center
        label.numberOfLines = 0
        label.lineBreakMode = .byTruncatingMiddle//文章过长省略方式
        //文字大小自适应,自动改变大小
//        label.adjustsFontSizeToFitWidth = true
        
        //富文本 NSFontAttributeName(字体大小,种类) //NSForegroundColorAttributeName(字体颜色)
        // NSBackgroundColorAttributeName(字体背景颜色)
        let attributeString = NSMutableAttributedString(string: "杰杰杰杰dfsagdgadslgjsdl;g")
        attributeString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue-Bold", size: 15)!,range: NSMakeRange(0,6))
        attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue, range: NSMakeRange(7, 14))
//        attributeString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.red, range: NSMakeRange(14, 25))
        label.attributedText = attributeString
        self.view.addSubview(label)
    }

8.tableView以及自定义cell

override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.CreateTableView()
    }
    
    func CreateTableView(){
        let tableView = UITableView.init(frame: CGRect(x: 0, y: 64, width: self.view.frame.width, height: self.view.frame.height - 64))
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "cell")
        tableView.register(MyTableCell.classForCoder(), forCellReuseIdentifier: "qwert")
        self.view.addSubview(tableView)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
      if indexPath.row == 4 {
         let cellcx = MyTableCell(style: UITableViewCellStyle.default, reuseIdentifier: "qwert")
            cellcx.myTitle.text = "ziyouzizai"
//            cellcx.contentView.addSubview(cellcx.myTitle)
            return cellcx
        } else {
            let cellID:String = "cell"
            let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: cellID)
            cell.textLabel?.text = "this is my first swift tableview"
            return cell
        }

    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
}

class MyTableCell: UITableViewCell {
    
//    lazy var myTitle:UILabel = {
//        let title = UILabel()
//        title.font = UIFont.systemFont(ofSize: 13)
//        title.textColor = UIColor.lightGray
//        title.textAlignment = .left
//        title.frame = CGRect(x: 5, y: 5, width: 80, height: 15)
//        return title
//    }()
 
    var myTitle:UILabel!
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        if !self.isEqual(nil){
            myTitle = UILabel(frame: CGRect(x: 5, y: 5, width: 70, height: 15))
            myTitle.textColor = UIColor.blue
            myTitle.font = UIFont.systemFont(ofSize: 12)
            self.contentView.addSubview(myTitle)
        }
        
    }
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func awakeFromNib() {
        super.awakeFromNib()
    }

在这里说明一下,我在自定义cell中碰到了坑,按照原来oc的形式,在cellforrow方法里,我按照条件依次往下写,当碰到特殊情况时比如row== 4,再写特殊条件,在swift中是不可以的,会出现问题,结果不对,原因在于swift是在编译前就会计算运行顺序,直白说就是他会依次执行,而不会像oc那样全部编译完后,在运行的时候才会判断条件。
自定义cell里,如果用懒加载调用属性的话,用到了闭包(注释的),所以这里没法添加到cell里,只能在cellforrow里面添加了

swift自己摸索着学习,目前还有很多不了解的地方,也希望和大家一起慢慢学习,最后贴一下swift 基础的一些东西 点击我

你可能感兴趣的:(Swift学习之路)