2016-12-14 8 views
0

私は、テーブル(MACのCocoaアプリケーションで)このような見解を持っています"1"。あなたが2つの列を持っていればいいです。数字が上がると、このアプローチは煩雑になります。プログラムでこれを行うことはできますか?ここセット識別子は、プログラム

は一例であり:

import Cocoa 

class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource { 

private var dataModel = DataModel() 
private var answer = 0 
private var keyData: (Int, [Int]) = (0, []) { 
    didSet { 
     tbl.reloadData() 
    } 
} 

@IBOutlet weak var questionIndex: NSTextField! 
@IBOutlet weak var tbl: NSTableView! 
@IBAction func replay(_ sender: Any) { 
    dataModel = DataModel() 
    questionIndex.stringValue = "0:" 
    answer = 0 
    updateModel() 
} 

@IBAction func forward(_ sender: NSButton) { 
    if sender.tag == 1 { 
     answer += keyData.0 
    } 
    updateModel() 
} 

func updateModel() { 
    let group = dataModel.nextGroup() 
    if let g = group { 
     self.keyData = g 
     let s = questionIndex.stringValue 
     questionIndex.stringValue = String(Int(String(s.characters.dropLast()))! + 1) + ":" 
     return 
    } 
    let alert = NSAlert() 
    alert.messageText = "You did have \(answer) on your mind, didn't you?" 
    alert.runModal() 
} 

override func viewDidLoad() { 
    super.viewDidLoad() 
    for (n, col) in tbl.tableColumns.enumerated() { 
     col.identifier = String(n) 
    } 
    updateModel() 
} 

func numberOfRows(in tableView: NSTableView) -> Int { 
    return keyData.1.count/8 + 1 
} 

func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { 
    let colId = tableColumn!.identifier 
    let colIndex = Int(colId)! 
    let index = (row * 8) + colIndex 
    let cell = tbl.make(withIdentifier: colId, owner: self) as! NSTableCellView 
    if 0 <= index && index < keyData.1.count { 
     cell.textField!.integerValue = keyData.1[index] 
    } else { 
     cell.textField!.stringValue = "" 
    } 
    return cell 
} 

override var representedObject: Any? { 
    didSet { 
    // Update the view, if already loaded. 
    } 
} 

}

I手でセル識別子を割り当てられ、対応する列インデックス、それらを同一にするので、セルIDの間のマッピングを作成するようにしていると2D配列(基になるデータモデル)の列インデックス。アプリは正常に動作していますが、これらのIDをクリックアンドポイントで割り当てるのは嫌です。

完全なプロジェクトはここで見つけることができます:https://github.com/kindlychung/MysteriousNum

+0

識別子は、通常のインデックスではなく、あなたのテーブルに表示することができ、細胞の「タイプ」を示すために使用されていません。 「GroupCell」や「ItemCell」と同様です。 –

+0

ええ、数字で表すこともできますが。列挙型は、例えば、Intとすることができます。とにかく、識別子1はおそらく文字列 "1"です。 – qed

+0

しかしそれはポイントではありません。ポイントは**あなたが望むならば、どのように私はその識別子をプログラムで設定できます**、 "GroupCell"になります。 – qed

答えて

3

は、カスタムセルを作成し、次の行を使用して、それに初期化を追加します。

override init(style: UITableViewCellStyle, reuseIdentifier: String?) { 
    super.init(style: style, reuseIdentifier: reuseIdentifier) 
} 

このセルクラスを次のように登録します。

self.tableView.register(CustomCell.self, forCellReuseIdentifier: "customCell") 

も同じセルを使用してdequeueReusableCellのような:

tableView.dequeueReusableCell(withIdentifier: "customCell",for: indexPath) as! CustomCell 
+0

質問は明らかにmacOS(*** NS ** TableView *)です – vadian