I created a UITableView
and this is my code for it:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
// let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "SubjectCell")
let cell = SubjectCell(style: UITableViewCellStyle.default, reuseIdentifier: "SubjectCell")
cell.cellUIImage.image = UIImage(named: "menu.png")
// cell.cellUIImage = UIImageView(UIImage(named: "menu-32.png"))
if indexPath.row % 2 == 0{
cell.backgroundColor = UIColor.cyan
}
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
And my SubjectCell
class is the following:
import Foundation
import UIKit
class SubjectCell : UITableViewCell{
@IBOutlet var cellUIImage: UIImageView!
}
However, when I run this code, it crashes. Debugging, I noticed that cellUIImage is nil, so it crashes when it unwraps it. The IBOulet
is linked to my prototype cell.
The unwrapping thing is made by Xcode, and it shouldn't be nil because it is actually a cell UIImageView
.
Since the release of iOS storyboard design, you no longer have to subclass UITableViewCell
to create your custom cell.
In your storyboard, select the Prototype Cell, in the Attributes Inspector tab, give the custom cell an identifier
(for example: "YourCellIdentifier").
Next, (still in storyboard) select the UIImageView that you added to the custom cell, give it a tag number (for example: 1000)
Now add this code to cellForRowAt
method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"YourCellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
// Here is your desired image view.
UIImageView *yourImageView = [cell viewWithTag:1000];
return cell;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.