[英]Swift - TableView background image: how to center the image
I want to add a logo as a background image to my tableView
. 我想将徽标作为背景图像添加到
tableView
。 Image size is 50px, 50px. 图片大小为50像素,50像素。
I tried the code below, but this puts the image lower right corner. 我尝试了下面的代码,但这将图像放在右下角。
let imageView = UIImageView(image: UIImage(named: "logo"))
imageView.contentMode = .scaleAspectFit
imageView.layer.frame = CGRect(x: self.view.frame.midX, y: self.view.frame.midY, width: 50, height: 50)
let tableViewBackgroundView = UIView()
tableViewBackgroundView.addSubview(imageView)
self.tableView.backgroundView = tableViewBackgroundView
There are a few points about swift that are pretty key: 关于swift的几点要点很关键:
1) The x and y parameters in CGRect.init(x:y:width:height:) don't refer to the center of the imageView. 1)CGRect.init(x:y:width:height :)中的x和y参数不指向imageView的中心。 Instead, they are points in a coordinate system where (0, 0) is the Upper Left Corner of the view that the CGRect is being presented over, and
相反,它们是在一个坐标系中的点(0,0)是视图的左上角 ,所述的CGRect正在呈现结束,
2) UIImageView actually inherits from UIView, so because of this you can just say 2)UIImageView实际上是从UIView继承的,因此您可以这样说
tableView.backgroundView = imageView
You shouldn't have to fiddle around with any CGRects, I believe this code should work just fine, although you may have to fiddle with different contentMode properties to get it to display how you like. 您不必摆弄任何CGRect,我相信这段代码应该可以正常工作,尽管您可能不得不摆弄不同的contentMode属性以使其显示您的喜好。
let imageView = UIImageView(image: UIImage(named: "logo"))
imageView.layer.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
imageView.layer.frame.midX = tableView.layer.frame.midX
imageView.layer.frame.midY = tableView.layer.frame.midY
tableView.backgroundView = imageView
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.