2014年7月11日金曜日

SwiftコードだけでUITableViewを配置

Storyboardを使わずに、Swiftコードだけで
UIViewController に UITableView を配置する例

( UITableView を配置する母体となる UIViewController は
Storyboard上に存在している前提です )


import UIKit

class HogeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var tableView : UITableView = UITableView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        tableView.frame = CGRectMake(0, 45, self.view.bounds.size.width, 1000)
        self.view.addSubview(tableView)
        
        tableView.delegate = self
        tableView.dataSource = self

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // セルの数
    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int  {
        return 1
    }
    
    // セルの設定
    func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath:NSIndexPath!) -> UITableViewCell! {
        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
        cell.textLabel.text = "セル \(indexPath.row)番目"
        cell.detailTextLabel.text = "詳細"
        return cell;
    }
    
    // セルが選択されたときに呼ばれる
    func tableView(tableView: UITableView?, didSelectRowAtIndexPath indexPath:NSIndexPath!) {
        println("選択された \(indexPath.row)番目")
    }

}

動作確認環境
Xcode6beta3

2014年7月10日木曜日

Swfitでアプリ内共通変数 ( グローバル変数? )



AppDelegate.swift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
                            
    var window: UIWindow?
        
    var userId:Int = 0     //  <==== この変数を他のクラスからアクセスする

    func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
        // Override point for customization after application launch.



ViewController.swift (他のクラス)

class ViewController: UIViewController {
                            
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        // AppDelegateクラスのメンバー変数を参照する
        var app:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
        println(app.userId)

    }


動作環境
Xcode6beta3