2016-11-10 4 views
0

私の構造変数 "title"をUITableViewのセルテキストラベルとして表示しようとしていますが、これが可能かどうかは誰にも分かりますか?UITableViewセルに表示する構造変数を取得しますか? swift/xcode8

私は、文字列を使用する前にこれを達成しているが、私は、私は構造体に宣言しているところです。この文脈

に構造体変数の1つにアクセスするかどうかはわかりません

import Foundation 

struct Note { 
    var title: String 
    var text: String 

} 

class Notes { 

    var notes:[Note] 

    public static let sharedInstance = Notes() 

    private init() { 
     self.notes = [] 
    } 

    public func add(title1: String, text1: String) throws { 
     self.notes.append(Note(title: title1, text: text1)) 

    } 
} 

とこれは私が構造体への単純な値を追加し、構造体に

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "note1", for: indexPath) 

     let note1 = Notes.sharedInstance 
     try? note1.add(title1: "Hello", text1: "World") 
     print(note1) 

     if let label = cell.textLabel { 
     // I've been trying to get it to work on this line 
     //label.text = note1.notes(get title here?)[indexPath.row] 
     } 

     return cell 
    } 

答えて

1

閉じる「タイトル」変数の値を表示しようとしているコントローラクラスです!あなたは、そのタイトルを取得しようとする前に、配列要素を選択する必要があります。

if let label = cell.textLabel { 
    label.text = note1.notes[indexPath.row].title 
} 
+0

優れたああ!完璧に動作します、非常にありがとう:) – kerberonix

0
import UIKit 

struct Note { 
    var title: String 
    var text: String 

    init(title: String, text: String) { 
     self.title = title 
     self.text = text 
    } 

} 

class Notes { 

    var notes:[Note] = [] 
    public static let sharedInstance = Notes() 

    private init() { 
    self.notes = [] 
    } 

    public func add(title1: String, text1: String) throws { 
     notes.append(Note(title: title1, text: text1)) 
    } 

} 

class ViewController: UIViewController, UITableViewDataSource { 

    var note1 = Notes.sharedInstance 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     for i in 1...10 { 
      try! note1.add(title1: "dfsad \(i)", text1: "sdfsdfsd") 
     } 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    func numberOfSections(in tableView: UITableView) -> Int { 
     return 1 
    } 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return note1.notes.count 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! as UITableViewCell 
     cell.textLabel?.text = note1.notes[indexPath.row].title 
     return cell 
} 

} 

出力:

enter image description here 感謝:)

+0

これは素晴らしいです、ありがとう:) – kerberonix

+0

私の答えが有用だったら、投票を断念してください。 :) –

関連する問題