我有tableview
,如何在此单元格的左侧添加图片?
答案 0 :(得分:126)
cell.imageView.image = [UIImage imageNamed:@"image.png"];
更新: 就像Steven Fisher说的那样,这应该仅适用于具有UITableViewCellStyleDefault风格的单元格,这是默认样式。对于其他样式,您需要将UIImageView添加到单元格的contentView。
答案 1 :(得分:20)
试试这段代码: -
UIImageView *imv = [[UIImageView alloc]initWithFrame:CGRectMake(3,2, 20, 25)];
imv.image=[UIImage imageNamed:@"arrow2.png"];
[cell addSubview:imv];
[imv release];
答案 2 :(得分:13)
标准UITableViewCell已经包含UIImageView,如果设置了图像,它将显示在所有标签的左侧。您可以使用imageView属性访问它:
cell.imageView.image = someImage;
如果由于某种原因标准行为不符合您的需求(请注意您可以自定义该标准图像视图的属性),那么您可以将自己的UIImageView添加到单元格中,正如Aman在答案中所建议的那样。但在这种方法中,您必须自己管理单元格的布局(例如,确保单元格标签不与图像重叠)。并且不要直接将子视图添加到单元格 - 将它们添加到单元格的contentView:
// DO NOT!
[cell addSubview:imv];
// DO:
[cell.contentView addSubview:imv];
答案 3 :(得分:6)
对于我的Swift用户,以下是您需要的代码:
let imageName = "un-child-rights.jpg"
let image = UIImage(named: imageName)
cell.imageView!.image = image
答案 4 :(得分:1)
Swift 4解决方案:
cell.imageView?.image = UIImage(named: "yourImageName")
答案 5 :(得分:0)
其他人的所有好的答案。您可以通过以下两种方式解决此问题:
直接来自您必须以编程方式控制imageview维度的代码
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "xyz", for: indexPath)
...
cell.imageView!.image = UIImage(named: "xyz") // if retrieving the image from the assets folder
return cell
}
从故事板中,您可以使用属性检查器&实用程序窗格中的大小检查器,用于调整定位,添加约束和指定尺寸
在故事板中,将imageView对象添加到具有所需尺寸的单元格内容视图中,并在属性检查器中向视图(imageView)添加标记。然后在viewController中执行以下操作
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "xyz", for: indexPath)
...
let pictureView = cell.viewWithTag(119) as! UIImageView //let's assume the tag is set to 119
pictureView.image = UIImage(named: "xyz") // if retrieving the image from the assets folder
return cell
}
答案 6 :(得分:0)
Swift 5解决方案
cell.imageView?.image = UIImage.init(named: "yourImageName")