m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

swiftの学習(tableviewでセルのカスタマイズ)

通常の方法

f:id:m_shige1979:20141124103549p:plain

画像とかいろいろと設定できるけどなんかひねりが欲しい場合など厳しいのかもしれない

ソース
//
//  ViewController.swift
//  swiftSample15
//
//  Created by 松本繁治 on 2014/11/24.
//  Copyright (c) 2014年 m_shige1979. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    
    var tableview:UITableView?
    var alert = UIAlertView()
    var items = [Dictionary<String, String>]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let screenHeight = UIScreen.mainScreen().bounds.size.height
        let screenWidth = UIScreen.mainScreen().bounds.size.width
        
        self.tableview = UITableView(frame: CGRect(x: 0, y: 60, width: screenWidth, height: screenHeight))
        self.tableview!.dataSource = self
        self.tableview!.delegate = self
        
        self.view.addSubview(self.tableview!)
        
        println("height = \(screenHeight)")
        println("width = \(screenWidth)")
        
        alert.title = "sample"
        alert.addButtonWithTitle("OK")
        
        items.append(
            [
                "name": "りんご",
                "detail": "テスト1"
            ]
        )
        
        items.append(
            [
                "name": "みかん",
                "detail": "テスト2"
            ]
        )
        
        items.append(
            [
                "name": "すいか",
                "detail": "テスト3"
            ]
        )
        
        items.append(
            [
                "name": "めろん",
                "detail": "テスト4"
            ]
        )
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        // リストの件数を返す1
        return  items.count
    }
    
    // セルをitemsから設定する処理
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")!
        cell.textLabel?.text = items[indexPath.row]["name"]!
        cell.detailTextLabel?.text = items[indexPath.row]["detail"]
        cell.imageView?.image = UIImage(named: "sample.jpeg")
        return cell;
    }
    
    // セルをクリックした時に発生するイベント
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        alert.message =  items[indexPath.row]["detail"]!
        alert.show()
    }


}



カスタムセルを作成する

シングルページアプリケーションを作成し、tableviewを追加して、datasourceなどを割り当てておく

f:id:m_shige1979:20141124115222p:plain

CustomCell.swift

関連付けるラベルなどはまだ設定しない

//
//  CustomCell.swift
//  swiftSample16
//
//  Copyright (c) 2014年 m_shige1979. All rights reserved.
//

import UIKit

class CustomViewCell: UITableViewCell {
    
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    override init?(style: UITableViewCellStyle, reuseIdentifier: String!) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }
}
tableviewにtabieviewcellを追加

f:id:m_shige1979:20141124115859p:plain

tabieviewcellにアイテムを追加

f:id:m_shige1979:20141124120422p:plain

tabieviewcellをクラスのCustomViewCellへ設定

f:id:m_shige1979:20141124120733p:plain

CustomViewCellに紐付け

f:id:m_shige1979:20141124120946p:plain

tabieviewcellのIdentifierを設定

f:id:m_shige1979:20141124121336p:plain

ViewController.swift
//
//  ViewController.swift
//  swiftSample16
//
//  Copyright (c) 2014年 m_shige1979. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableview: UITableView!
    
    var alert = UIAlertView()
    var items = [Dictionary<String, String>]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        alert.title = "sample"
        alert.addButtonWithTitle("OK")
        
        items.append(
            [
                "name": "りんご",
                "detail": "テスト1"
            ]
        )
        
        items.append(
            [
                "name": "みかん",
                "detail": "テスト2"
            ]
        )
        
        items.append(
            [
                "name": "すいか",
                "detail": "テスト3"
            ]
        )
        
        items.append(
            [
                "name": "めろん",
                "detail": "テスト4"
            ]
        )
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        // リストの件数を返す1
        return  items.count
    }
    
    // セルをitemsから設定する処理
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as CustomViewCell
        
        cell.myLabel1?.text = items[indexPath.row]["name"]!
        cell.mylabel2?.text = items[indexPath.row]["detail"]!
        cell.myImage.image = UIImage(named: "sample.jpeg")
        
        return cell;
    }
    
    // セルをクリックした時に発生するイベント
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        alert.message =  items[indexPath.row]["detail"]!
        alert.show()
    }


}
結果

f:id:m_shige1979:20141124121905p:plain

所感

iphoneのサイズに合わせてある程度の調整は必要だけど、なんとかなりそうな感じ
イベントの追加などはしていないけどボタンの追加などの対応もそのうちやるかも…

ボタンの装飾なんとかしたいな〜