Swift:UIKit中Demo(一)

关于Swift的基本概念及语法知识。我在前面的章节中已经介绍了非常多。这一节和下一节主要有针对性的解说Swift在实际UIKit开发中的使用场景及注意点。先来看看Demo的终于效果图。


Demo分析:

1. 界面上面有三个button,他们的宽度不一致。

2. 点击每一个button的时候。以下有红色下划线跟着"走动"。

一、 Storyboard中的设计



注意到,这个红色下划线是任意摆放的。没有刻意的设置它的位置及宽度。而这个红色下划线也就是一个简单的UIView。


二、 拖线工作

在本例中,有三个IBOutlet连线工作,代码例如以下:

@IBOutlet weak var firstButton: UIButton!
@IBOutlet weak var underline: UIView!
@IBAction func btnClick(sender: UIButton)
1. 之所以连线第一个button。是由于程序刚启动的时候,应该默认运行点击第一个button的事件,以此来改变红色下划线的位置及宽度。

2. underline这个UIView便是这个红色下划线。

关于上面 "!" 使用假设有什么疑问的话。能够參照 Swift:可选类型(Optional)

3. btnClick 这种方法就是三个button的共同点击事件。


三、 button点击事件分析

代码例如以下:

UIView.animateWithDuration(0.25, animations: { () -> Void in
self.selectedButton?.selected = false
sender.selected = true
self.selectedButton = sender
            
// 要先设置宽高,后设置位置,不然效果有影响
self.underline.frame.size.width = sender.frame.size.width
self.underline.center.x = sender.center.x
self.underline.frame.origin.y = CGRectGetMaxY(sender.frame) + 5
   })

代码中的前三句是经典的button点击三部曲(用来切换button的点击状态),后面三句就是用来实现终于的动画;程序简单明了,我就不做过多的解释工作。

仅仅想说明两点:

1. selectedButton 是定义的一个属性,用来指向被选中的button。

2. self.selectedButton?.selected = false 事实上是代码的简写形式。也能够写成以下的形式,他们是等价的。

if(self.selectedButton != nil){
     self.selectedButton.selected = false
}
注意: 在推断语句中,我们使用了比較推断,即self.selectedButton 是否为nil。

在objective-c中,或许大家会直接书写成 if(self.selectedButton) 进行推断就能够了。可是在Swift中这样书写是错误的。

由于Swift是类型安全的语言,推断条件必须是bool值。即使你在Swift中写成 if(1) 这种推断条件也是失败的。


四、 默认选中第一个button

这个操作事实上是非常easy的。仅仅要在viewDidLoad中加一句

self.btnClick(self.firstButton)

但会出现下划线默认会移动的效果。由于下划线默认不在第一个button的下方。所以运行动画,会移动过去。

解决的办法就是在默认载入的时候,禁止动画就可以。所以终于的代码例如以下:

class ViewController: UIViewController {
    weak var selectedButton: UIButton!
    @IBOutlet weak var firstButton: UIButton!
    @IBOutlet weak var underline: UIView!
    @IBAction func btnClick(sender: UIButton) {
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            self.selectedButton?

.selected = false sender.selected = true self.selectedButton = sender self.underline.frame.size.width = sender.frame.size.width self.underline.center.x = sender.center.x self.underline.frame.origin.y = CGRectGetMaxY(sender.frame) + 5 }) } override func viewDidLoad() { super.viewDidLoad() // 界面刚载入进来的时候。禁止动画 UIView.setAnimationsEnabled(false) self.btnClick(self.firstButton) UIView.setAnimationsEnabled(true) } }


原文地址:https://www.cnblogs.com/brucemengbm/p/7045320.html