Hiển thị dữ liệu lên TableView trên iOS với Objective-C

TableView là một trong những điều khiển phổ biến trong các ứng dụng iOS. Khi nói đến TableView, chúng ta liên tưởng đến một bảng có nhiều hàng và cột. Tuy nhiên, trên iOS, do màn hình thiết bị nhỏ, việc hiển thị bảng nhiều cột không phải là tối ưu. Vì vậy, Apple mặc định chỉ cho phép hiển thị một cột và cung cấp một số kiểu để bạn có thể hiển thị thêm thông tin bên cạnh thông tin chính.

Ở dạng đơn giản nhất, TableView hiển thị giống một danh sách:

Apple cũng cung cấp một số dạng hiển thị định nghĩa trước phức tạp hơn, ví dụ:

(Hình minh họa này lấy từ website của Apple)

Và cả tùy biến theo ý thích, nếu các kiểu có sẵn không phù hợp nhu cầu sử dụng của bạn.

Trong iOS, mỗi TableView là một instance của lớp  UITableView. Trên macOS, lớp tương ứng là  NSTableView. Nếu bạn quan tâm đến việc hiển thị dữ liệu lên Table View trên macOS, hãy bấm vào đây.

Mình cũng có một bài viết về chủ đề này bằng ngôn ngữ Swift. Nếu bạn quan tâm đến việc đổ dữ liệu lên UITableView bằng Swift , hãy bấm vào đây.

Bài này, mình hướng dẫn hiển thị dữ liệu lên TableView trên iOS với Objective-C. Dữ liệu hiển thị là một danh sách 5 sinh viên có những thuộc tính ID, NameAddress. Dữ liệu sẽ được lưu trong một mảng NSMutableArray, sau đó, đổ vào TableView. Khi chạy, màn hình sẽ hiển thị cả ba thông tin, bao gồm Name in đậm ở trên và ID – Address in nhỏ hơn ở ngay dưới Name, như hình:

Hiển thị dữ liệu lên TableView trên iOS
Hiển thị dữ liệu lên TableView trên iOS

Hướng dẫn

  • Bước 1: Từ Xcode, bấm File > New > Project…
  • Bước 2: Chọn iOS > Single View App, bấm Next
  • Bước 3: Nhập tên Project vào Product NameLanguage chọn Objective-C. Bấm Next và chọn nơi lưu Project.

Giao diện

Từ Project navigator, bấm vào file Main.Storyboard. Sau đó bấm vào nút Library, tìm và kéo thả Label vào View.

Chọn Label, ở cửa sổ Attributes inspector, nhập Student List vào bên dưới ô thuộc tính Text Plain. Ở thuộc tính Font, chọn Style Semibold Size 45.

Bấm nút Add New Constraints, chúng ta sẽ neo Label cố định để nó không bị nhảy lung tung trên những màn hình khác nhau.

Ở cửa sổ Add New Constraints, nhập 0 cho ô trên và 20 cho ô trái, như hình:

Bạn phải đảm bảo hai đoạn thẳng màu đỏ từ 2 ô trên nối vào ô ở giữa hiển thị. Nếu không hiển thị thì bạn bấm vào nó. Xong bấm Add 2 Constraints.

Làm lại như trên, tìm và kéo thả Table View vào View. Neo với Constraints lần lượt là: trên 10, trái, phải và dưới 0.

Kế tiếp, chúng ta sẽ tạo prototype cho mỗi ô hiển thị trên Table View. Cho hiển thị cửa sổ Document Outline, từ Library, tìm và kéo thả Table View Cell vào bên dưới Table View:

Bây giờ, bên trong Table View sẽ xuất hiện phần tử Table View Cell. Bấm vào Table View Cell và mở Attributes inspector, chọn Subtitle cho Style và nhập myCell vào Identifier:

Sau khi xong, bạn sẽ nhìn thấy giao diện thiết kế sẽ hiển thị như hình:

Tạo connection với mã

Trong mã, chúng ta sẽ thao tác với Table View, do đó, chúng ta sẽ tạo một connection từ giao diện Table View với mã.

Bấm vào nút Assistant editor, phần viết mã của cửa sổ Xcode sẽ bị chia làm hai, một bên là Document Outline, một bên là file code. Tìm file code ViewController.h, rồi bấm phải Table View kéo rê chuột vào phần @interface của file code, một cửa sổ popup hiện ra, nhập tên là myTableView, Connection chọn Outlet rồi bấm Connect.

Tạo lớp Student

Từ cửa sổ Project navigator, bấm phải thư mục Project, chọn New File… Sau đó, chọn Header File, đặt tên là Student.h và viết đoạn mã sau cho file:

@interface Student : NSObject
 
 @property (nonatomic, retain) NSString* studentID;
 @property (nonatomic, retain) NSString* studentName;
 @property (nonatomic, retain) NSString* studentAddress;
 
@end

Tương tự, tạo một file Student.m (Objective-C File) và viết đoạn mã sau:

#import <Foundation/Foundation.h>
#import "Student.h"
 
@implementation Student : NSObject
 
 @synthesize studentID = _studentID;
 @synthesize studentName = _studentName;
 @synthesize studentAddress = _studentAddress;
 
 -(id)init{
     self = [super init];
     
     return self;
 }
 
@end

Đây là lớp Student, mỗi đối tượng của lớp sẽ chứa dữ liệu của một sinh viên lấy từ database. (Mình không bàn việc kết lấy dữ liệu từ database ở bài này). Lớp có 3 thuộc tính ID, Tên và Địa chỉ.

Tạo lớp MyData

Lớp này giả lập một model trả dữ liệu từ database lên. Trong lớp này, chúng ta sẽ tạo một class method tên getStudentList trả về một mảng NSMutableArray gồm 5 object Student.

Tạo hai file MyData.hMyData.m và thêm vào đoạn mã sau:

MyData.h:

#import "Student.h"
 
@interface MyData : NSObject
 
 +(NSMutableArray *)getStudentList;
 
@end

MyData.m:

#import <Foundation/Foundation.h>
#import "MyData.h"
 
@implementation MyData : NSObject
 
 +(NSMutableArray *)getStudentList {
     
     NSMutableArray *studentArray = [[NSMutableArray alloc] initWithCapacity: 5];
 
     Student *std1 = [[Student alloc] init];
     std1.studentID = @"S01";
     std1.studentName = @"Anna K. Behrensmeyer";
     std1.studentAddress = @"711-2880 Nulla St Mankato Mississippi 96522";
     
     Student *std2 = [[Student alloc] init];
     std2.studentID = @"S02";
     std2.studentName = @"Blaise Pascal";
     std2.studentAddress = @"7292 Dictum Av. San Antonio MI 47096";
     
     Student *std3 = [[Student alloc] init];
     std3.studentID = @"S03";
     std3.studentName = @"Caroline Herschel";
     std3.studentAddress = @"191-103 Integer Rd. Corona New Mexico 08219";
     
     Student *std4 = [[Student alloc] init];
     std4.studentID = @"S04";
     std4.studentName = @"Cecilia Payne-Gaposchkin";
     std4.studentAddress = @"P.O. Box 887 2508 Dolor. Av. Muskegon KY 12482";
     
     Student *std5 = [[Student alloc] init];
     std5.studentID = @"S05";
     std5.studentName = @"Dorothy Hodgkin";
     std5.studentAddress = @"935-9940 Tortor. Street Santa Rosa MN 98804";
     
     [studentArray addObject:std1];
     [studentArray addObject:std2];
     [studentArray addObject:std3];
     [studentArray addObject:std4];
     [studentArray addObject:std5];
     
     return studentArray;
 }
 
@end

Hiển thị dữ liệu

Để đổ dữ liệu lên Table View, lớp ViewController phải implement protocol UITableViewDataSource và định nghĩa hai phương thức:

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath;
- (NSInteger)tableView:(UITableView *)tableView 
         numberOfRowsInSection:(NSInteger)section;

Chúng ta cũng sẽ khai báo biến myData, biến này trỏ đến dữ liệu mà chúng ta muốn sử dụng.

Viết đoạn mã sau cho file ViewController.h:

#import <UIKit/UIKit.h>
#import "Student.h"
#import "MyData.h"
 
@interface ViewController : UIViewController
 
@end

Ở file ViewController.m, chúng ta sẽ lấy dữ liệu gán vào biến myData, sau đó, xác định datasource của Table View là self, tức ViewController là nguồn xử lý dữ liệu cho TableView. Cuối cùng, hiện thực hai phương thức như trên đã nói để hiển thị dữ liệu lên TableView:

#import "ViewController.h"
 
@interface ViewController () <UITableViewDataSource> {
     NSMutableArray *myData;
     __weak IBOutlet UITableView *myTableView;
}
 
@end
 

@implementation ViewController

 - (void)viewDidLoad {
     [super viewDidLoad];
     // Do any additional setup after loading the view.
     myData = MyData.getStudentList;
     
     myTableView.dataSource = self;
     
 }
 
 - (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
     
     // Get student name
     NSString *studentName = [[myData objectAtIndex:indexPath.row] studentName];
     
     // Get student ID and address, and concatenate string as ID - Address
     NSMutableString *studentIDAndAddress = [[NSMutableString alloc] initWithString:[[myData objectAtIndex:indexPath.row] studentID]];
     [studentIDAndAddress appendString:@" - "];
     [studentIDAndAddress appendString:[[myData objectAtIndex:indexPath.row] studentAddress]];
     
     NSString *myCellID = @"myCell";
     
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:myCellID forIndexPath:indexPath];
     
     cell.textLabel.text = studentName;
     
     cell.detailTextLabel.text = studentIDAndAddress;
     
     return cell;
 }
 
 - (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
     return [myData count];
 }
 
@end

Như vậy là chúng ta đã hoàn tất việc đổ dữ liệu vào TableView trên iOS.

Bạn có thể tải xuống project mẫu của mình tại: https://github.com/ngthanhbinh85/Populating-the-UITableView-iOS-Objective-C

3 Comments

Bình luận

Bình luận Facebook

lời bình luận