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 基础的一些东西 点击我

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,185评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,652评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,524评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,339评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,387评论 6 391
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,287评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,130评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,985评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,420评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,617评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,779评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,477评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,088评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,716评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,857评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,876评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,700评论 2 354

推荐阅读更多精彩内容

  • 转载自:https://github.com/Tim9Liu9/TimLiu-iOS 目录 UI下拉刷新模糊效果A...
    袁俊亮技术博客阅读 11,923评论 9 105
  • 如果有人读了很多书,却无所进益,可能是他少读了一本叫生活的书,世间万般苦,那一种书中没有。心怀仁心,怎么可能对众人...
    艺叶亦华阅读 190评论 0 0
  • 深深的感恩老天爷给予的一切!感恩生命中出现的人事物*感恩此时此刻心中满满的感恩*感恩生命给予的恩赐*
    晴晴zhang阅读 297评论 0 0
  • 在茫茫画家海洋中,克里姆特让人觉得眼前一亮,他那大片大片的金色,任务造型特别修长,用了那么多金色但不让人觉得庸俗。...
    shamumu阅读 3,100评论 0 3
  • 2017年3月24日,今天是我来北京的第245天.---Ivy 刚刚在朋友圈看到同事发了一篇文章,其实这个话题自己...
    读物博主牧歌阅读 686评论 5 5