Jacky Wrong Jacky Wrong - 1 month ago 25
Swift Question

iOS swift3 tableview simple display value

I am a stduent and very beginner of swift3. In here, I just want to display "First","Second","Third" in the tableview and it does not look good.

The tutorial from the youtube is swift2 and I try to convert into swift3. I think the problem is related to code:

let Cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell


I try hard to search like https://www.codeschool.com/blog/2016/09/14/evolving-to-swift-3/ but I dont know what happen. The Xcode cannot detect any error of the code and it can run. The tableview in iphone simulator is empty or whole screen is black.

I use the navigation controller to implement it. The class in viewcontoller and iderntifer in table view cell are well set in the root view contoller. Please help me. Thanks.

import Foundation
import UIKit

class ViewController: UITableViewController {

var Array = [String]()

override func viewDidLoad() {
super.viewDidLoad()

Array = ["First","Second","Third"]

}

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

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

Cell.textLabel?.text = Array[indexPath.row]

return Cell
}


}

The result of running the code. Click me to see.

Result in console:

2016-10-24 01:10:38.111399 TableApp[27276:2609723] subsystem: com.apple.UIKit, category: HIDEventFiltered, enable_level: 0, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 1, privacy_setting: 2, enable_private_data: 0
2016-10-24 01:10:38.114012 TableApp[27276:2609723] subsystem: com.apple.UIKit, category: HIDEventIncoming, enable_level: 0, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 1, privacy_setting: 2, enable_private_data: 0
2016-10-24 01:10:38.122822 TableApp[27276:2609719] subsystem: com.apple.BaseBoard, category: MachPort, enable_level: 1, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 0, privacy_setting: 0, enable_private_data: 0
2016-10-24 01:10:38.138706 TableApp[27276:2609660] subsystem: com.apple.UIKit, category: StatusBar, enable_level: 0, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 1, privacy_setting: 2, enable_private_data: 0
2016-10-24 01:10:38.200 TableApp[27276:2609660] *** Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3599.6/UITableView.m:8035
2016-10-24 01:10:38.203 TableApp[27276:2609660] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView (<UITableView: 0x7fbac906bc00; frame = (0 0; 375 667); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x61000004e400>; layer = <CALayer: 0x610000235ce0>; contentOffset: {0, -64}; contentSize: {375, 132}>) failed to obtain a cell from its dataSource (<TableApp.GetStringViewController: 0x7fbac8d06180>)'
*** First throw call stack:
(
0 CoreFoundation 0x000000010fab034b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x000000010c9dc21e objc_exception_throw + 48
2 CoreFoundation 0x000000010fab4442 +[NSException raise:format:arguments:] + 98
3 Foundation 0x000000010c572edd -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 195
4 UIKit 0x000000010d429ff2 -[UITableView _configureCellForDisplay:forIndexPath:] + 222
5 UIKit 0x000000010d435c10 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 860
6 UIKit 0x000000010d435e07 -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 74
7 UIKit 0x000000010d409871 -[UITableView _updateVisibleCellsNow:isRecursive:] + 3295
8 UIKit 0x000000010d43f189 -[UITableView _performWithCachedTraitCollection:] + 110
9 UIKit 0x000000010d4259e3 -[UITableView layoutSubviews] + 222
10 UIKit 0x000000010d38d344 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1237
11 QuartzCore 0x0000000112875cdc -[CALayer layoutSublayers] + 146
12 QuartzCore 0x00000001128697a0 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
13 QuartzCore 0x000000011286961e _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
14 QuartzCore 0x00000001127f762c _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 280
15 QuartzCore 0x0000000112824713 _ZN2CA11Transaction6commitEv + 475
16 QuartzCore 0x0000000112825083 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 113
17 CoreFoundation 0x000000010fa54e17 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
18 CoreFoundation 0x000000010fa54d87 __CFRunLoopDoObservers + 391
19 CoreFoundation 0x000000010fa394b6 CFRunLoopRunSpecific + 454
20 UIKit 0x000000010d2c2db6 -[UIApplication _run] + 434
21 UIKit 0x000000010d2c8f34 UIApplicationMain + 159
22 TableApp 0x000000010c3fb5bf main + 111
23 libdyld.dylib 0x00000001109da68d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

Joe Joe
Answer

Try This code: Code tested in Swift 3.

Note: As you mentioned you just started programming Swift 3.I created a tableView programmatically. Just,copy below code and paste in to your viewController.run the project...

    import UIKit

    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    private let Array: NSArray = ["First","Second","Third"]
    private var myTableView: UITableView!

    override func viewDidLoad() {
    super.viewDidLoad()

    // Status Bar 
    let barHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height 

    // View 
    let displayWidth: CGFloat = self.view.frame.width
    let displayHeight: CGFloat = self.view.frame.height

    // TableView 
    myTableView = UITableView(frame: CGRect(x: 0, y: barHeight, width: displayWidth, height: displayHeight - barHeight))

    // Cell 
    myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")

    // DataSource 
    myTableView.dataSource = self

    // Delegate 
    myTableView.delegate = self

    // View 
    self.view.addSubview(myTableView)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("Num: \(indexPath.row)")
    print("Value: \(Array[indexPath.row])")
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath) 

    cell.textLabel!.text = "\(Array[indexPath.row])"

    return cell
 }

}

Output: enter image description here