Swift体验

2018-06-20  本文已影响0人  Mark_Liu_JS

1.单个按钮的实现

1.1 按钮内容的实现

Snip20180620_1.png Snip20180620_2.png

1.2 按钮的交互

Snip20180620_3.png Snip20180620_5.png

 @IBAction func touchCard(_ sender: UIButton) {
        flipCard(withEmoji: "🏄🏻‍♂️", on: sender)
    }
  
/// 设置按钮的内容
  func flipCard(withEmoji emoji: String, on button: UIButton) -> Void {
        
        // 如果有表情,清空,否之设置
        
        if button.currentTitle == emoji {
            
            button.setTitle("", for: .normal)
            button.backgroundColor = #colorLiteral(red: 0.9471735358, green: 0.5837251544, blue: 0.191911608, alpha: 1)
        
        } else {
            
            button.setTitle(emoji, for: .normal)
            button.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        }
    }

2.两个按钮的实现

2.1 拷贝按钮

Snip20180620_6.png Snip20180620_7.png

2.2 实现第二个按钮的交互

  @IBAction func touchSecondCard(_ sender: UIButton) {
        
        flipCard(withEmoji: "🏄🏻‍♂️", on: sender)
    }

3. 显示点击次数

3.1 增加显示标签

/// 点击次数(属性)
    @IBOutlet weak var flipCountLabel: UILabel!

var flipCount: Int = 0

 /// 点击按钮(事件)
    @IBAction func touchCard(_ sender: UIButton) {
        
        flipCount += 1
        flipCountLabel.text = "Flips: \(flipCount)"
        
        flipCard(withEmoji: "🍆", on: sender)
    }
    
    @IBAction func touchSecondCard(_ sender: UIButton) {
        
        flipCount += 1
       flipCountLabel.text = "Flips: \(flipCount)"
        
        flipCard(withEmoji: "🏄🏻‍♂️", on: sender)
    }

3.2 didSet

 var flipCount: Int = 0 {
        
        didSet {
            
            flipCountLabel.text = "Flips: \(flipCount)"
        }
    }

4. 多个按钮的实现

4.1 实现集合连接

Snip20180620_9.png
@IBOutlet var cardButtons: [UIButton]!
Snip20180620_11.png Snip20180620_12.png Snip20180620_14.png Snip20180620_10.png

4.2 修改已连接属性名的处理

Snip20180620_15.png Snip20180620_16.png

4.3 获得每个按钮在集合中的位置


  /// 点击按钮(事件)
    @IBAction func touchCard(_ sender: UIButton) {
        
        flipCount += 1
        let index = cardButtons.index(of: sender) ?? 0
       print(index)
 
    }

4.4 实现多表情

 /// 表情符号集合
    var emojiChoices = ["🐱", "🍐", "🚐", "👻"]

 /// 点击按钮(事件)
    @IBAction func touchCard(_ sender: UIButton) {
     
        flipCount += 1
        let index = cardButtons.index(of: sender) ?? 0
        flipCard(withEmoji: emojiChoices[index], on: sender)
    }

小结

上一篇 下一篇

猜你喜欢

热点阅读