2017-03-10 69 views
0

我是新的xcode/swift。我遇到了在iPhone 4英寸屏幕中用UITableViewCell替換UIImageView的問題。我用Assets.xcassets中的正確值:640,750,1242像素寬度嵌入了圖像。uitableviewcell uiimage在4英寸自動佈局問題iphone

TableView和ContentView約束[尾隨空間到,頂層空間到底層空間頂層空間]都是從xCode完成的。

這是我如何實現代碼如下cellForRowAt使用的UIImageView:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let identifier = "reusedCell" 
     var cell = tableView.dequeueReusableCell(withIdentifier: identifier) 

     if(cell == nil) { 
      cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: identifier) 
     } 

     let image = UIImage(named: "TableView\(indexPath.row)") 
     let imageView = UIImageView(image: image) 
     cell?.addSubview(imageView) 
     imageView.contentMode = UIViewContentMode.scaleAspectFill 
     imageView.clipsToBounds = true 

     return cell! 
} 

Click here to see images are cut from right side

圖像會以4.7大小正確,和5.5英寸屏幕的iPhone,但不是在iphone 5,5S和SE。

任何幫助/建議高度讚賞。 感謝

回答

0

你需要作出約束imageView

let imageView = UIImageView(image: image) 
cell?.addSubview(imageView) 
imageView.translatesAutoresizingMaskIntoConstraints = false 
// for example 
imageView.anchor(topAnchor, left: cell.leftAnchor, bottom: cell.bottomAnchor, right: cell.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0) 

或者創建一個自定義單元格

class CustomTableViewCell: UITableViewCell { 
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) { 
     super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) 

     setupViews() 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

    let let imageView: UIImageView = { 
     let imgView = UIImageView() 
     imgView.translatesAutoresizingMaskIntoConstraints = false 
     imgView.contentMode = UIViewContentMode.scaleAspectFill 
     imgView.clipsToBounds = true 


     return imgView 
    }() 

    func setupViews() { 
     addSubview(imageView) 
     imageView.anchor(topAnchor, left: cell.leftAnchor, bottom: cell.bottomAnchor, right: cell.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0) 
    } 
} 

然後更換你的函數的tableView到:

let identifier = "reusedCell" 
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: identifier) as ! CustomTableViewCell 

     let image = UIImage(named: "TableView\(indexPath.row)") 
     cell.imageView.image = image 

     return cell! 
}