我在UIViewController
中有一个UIImageView
,在我自己的自定义单元格类中定义了一个原型单元格。我的右上角有TableView
,有顶部和尾部边距限制,以及固定的宽度和高度:
问题是,当我运行程序时,imageView
已创建,但cellForRowAtIndexPath
超大:
在研究了本网站上的一些类似问题之后,我得出的结论是:
单元格的imageView仅在您指定时显示并调整大小 想象一下。
我已经在自定义单元格类和cell.imageView?.frame = CGRectMake(300, 52, 292, 136)
cell.imageView?.clipsToBounds = true
cell.contentView.addSubview(cell.imageView!)
函数中尝试了以下代码:
imageView
我是否遗漏了某些内容或我该怎样做才能使{{1}}达到我已限制的大小?
提前谢谢!
答案 0 :(得分:1)
UIView具有属性contentMode - 尝试将其定义为ScaleToFill:
self.someImage.contentMode = .ScaleToFill
答案 1 :(得分:1)
感谢大家的帮助!
我通过引用自定义单元格的通用imageView?
犯了一个愚蠢的错误,而不是我用不同名称制作的IB Outlet
。
错:
cell.imageView?.image = UIImage(named: "whatever name")
右:
cell.dogImageView.image = UIImage(named: "labrador")
答案 2 :(得分:0)
出于兴趣,固定的宽度和高度限制是什么值?由于视图控制器的大小不同,很难区分界面构建器和设备屏幕截图。
我的建议是取消固定的宽度和高度限制,而是:
•将图像视图的底部固定在单元格的底部 - 这样可以使图像视图显示高度。
•为图像视图添加宽高比约束 - 这会根据图像视图的高度为图像视图提供宽度。
这意味着即使您最终更改单元格的高度,图像视图也始终适合单元格。
使用原型单元格和UITableViewCell子类的荣誉 - 我完全赞同这种方法!
答案 3 :(得分:0)
虽然我同意您使用自定义单元格类,但您的代码看起来很模糊。这样做是为了尝试下载所有图像集,如果无法下载,它将用保存在资源上的图像占位符替换图像。所有图像在加载时都具有相同的大小。
您可以采取以下措施使其发挥作用。这是您的自定义类。
class SomeCell: UITableViewCell {
@IBOutlet weak var imgMain: UIImageView!
@IBOutlet weak var lblMain: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
imgMain.layer.cornerRadius = 5.0
imgMain.clipsToBounds = true
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configureCell(image: UIImage, text: String){
imgMain.image = image
lblMain.text = text
}
}
然后在你的ViewController上
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var somePics = ["http://www.something.com/pic1.jpg","http://www.something.net/pic2.jpg","http://www.something.com/pic3.jpg","http://www.something.com/pic4.jpg","http://www.something.net/pic5.jpg"]
var someTitles = ["Picture 1", "Picture 2", "Picture 3", "Picture 4", "Picture 5"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
// Do any additional setup after loading the view, typically from a nib.
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("SomeCell") as? SomeCell {
var img: UIImage!
let url = NSURL(string: somePics[indexPath.row])!
if let data = NSData(contentsOfURL: url) {
img = UIImage(data: data)
}else {
img = UIImage(named: "somePlaceholderpic")
}
cell.configureCell(img, text: someTitles[indexPath.row])
return cell
} else {
return SomeCell()
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return somePics.count
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
希望这会有所帮助。 :)