iOS & Swift 공부 - Customizing Cells in a TableView using .xib file(영)

김영채 (Kevin)·2021년 1월 31일
0

iOS & Swift

목록 보기
60/107
  • Add a new file in the Views folder

  • Add a CocoaToach file. For a tableview cell, it must be the subclass of "UITableViewCell"
  • When file is added, two new files will be added to your directory.

→ Xib (pronounced as "zib") file is a design file used by the MessageCell.swift.


→ Here, "Nib" is the old name for Xib.

→ awakeFromNib( ) initializes the xib file. Meaning however we customize the MessageCell.xib file, this method initializes it.

  • Try and customize the xib file as you wish.

  • Connect the objects you added in the xib file to the MessageCell.swift file as IBOutlets
  • The first step to use the custom design file (ex. xib file), is to register it in the viewDidLoad( )

(Be careful of the parameters → There are a bunch of register( ) methods that you can choose from)

→ cellNibName has been pre-configured in the Constants.swift file, to prevent hardcoding String values everytime. The name is "MessageCell"

→ forCellReuseIdentifier must also be configured.

(Just like giving an identifier for a Segue, xib files also can be given an identifier)

→ K.cellIdentifier is also pre-configured in the Constants file. The name is "ReusableCell"

→ By following the above steps, we have now "registered" our table view

  • Then, in the area where we implement the UITableViewDataSource protocol, we need to cast each cell "as MessageCell"

→ This way, each cell becomes the design of the xib file we configured earlier.

  • Now, in Main.storyboard, we can now delete the previously added "prototype cell" because we are no longer using it. From now on, we are using the custom-designed cell: "MessageCell.xib"

Optional : In my case, I'm making a chat bubble. To make the MessageCell look more like a bubble, we can tap into the below code.

Note: The Lines property for the Label must be set to 0 to present messages that go over a single line.

→ If we set the Line property to 0, no matter how long the message is, it will dynamically adjust.

profile
맛있는 iOS 프로그래밍

0개의 댓글