[iOS]UITableViewを使ってEmojiリストを作成


UITableViewを使ってEmojiリストを作成

参考資料

App Development with Swift - Apple

コード例

Emoji.swift
import UIKit

class Emoji{
    var symbol:String
    var name:String
    var description:String
    var usage:String

    init(symbol:String,name:String,description:String,usage:String){
        self.symbol = symbol
        self.name = name
        self.description = description
        self.usage = usage
    }
}

var emojis: [Emoji] = [
    Emoji(symbol: "😀", name: "Grinning Face",description: "A typical smiley face.", usage: "happiness"),
    Emoji(symbol: "😕", name: "Confused Face",description: "A confused, puzzled face.", usage: "unsure what to think; displeasure"),
    Emoji(symbol: "😍", name: "Heart Eyes",description: "A smiley face with hearts for eyes.",usage: "love of something; attractive"),
    Emoji(symbol: "👮", name: "Police Officer",description: "A police officer wearing a blue cap with a gold badge.", usage: "person of authority"),
    Emoji(symbol: "🐢", name: "Turtle", description:"A cute turtle.", usage: "Something slow"),
    Emoji(symbol: "🐘", name: "Elephant", description:"A gray elephant.", usage: "good memory"),
    Emoji(symbol: "🍝", name: "Spaghetti",description: "A plate of spaghetti.", usage: "spaghetti"),
    Emoji(symbol: "🎲", name: "Die", description: "A single die.", usage: "taking a risk, chance; game"),
    Emoji(symbol: "⛺️", name: "Tent", description: "A small tent.", usage: "camping"),
    Emoji(symbol: "📚", name: "Stack of Books",description: "Three colored books stacked on each other.",usage: "homework, studying"),
    Emoji(symbol: "💔", name: "Broken Heart",description: "A red, broken heart.", usage: "extremesadness"), Emoji(symbol: "💤", name: "Snore",description:"Three blue \'z\'s.", usage: "tired, sleepiness"),
    Emoji(symbol: "🏁", name: "Checkered Flag",description: "A black-and-white checkered flag.", usage:"completion")]


//抜粋 Apple Education "App Development with Swift" Apple Inc.
EmojiViewController.swift
import UIKit

class EmojiViewController: UITableViewController{

//表示するセル数の設定
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return emojis.count
    }


//セルに表示させる内容の設定
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        let emoji = emojis[indexPath.row]
        cell.textLabel?.text = "\(emoji.symbol) - \(emoji.name)"
        cell.detailTextLabel?.text = emoji.description
        return cell
    }
}

開発環境

Mac OS High Sierra / Swift 4.0 / Xcode 9.0

作成方法

1. プロジェクトを新規作成(今回は Emoji と設定)

2. ViewController.swift と Main.stroryboard内の View Controller を削除

3. EmojiViewController.swiftEmoji.swift を新規作成 & 上記コードに編集

4. Custom Classに EmojiViewController を設定

5. Emoji View Controller > Cell の Indentifier に Cell を設定

6. シミュレータを起動