[英]Programmatically center UIImage inside parent view vertically
I am on Swift 5.我在 Swift 5。
The goal is to center a UIImageView
vertically inside a view.目标是将
UIImageView
在视图内垂直居中。 Currently it looks like目前它看起来像
Note all the image bubbles are running off of the cell.请注意,所有图像气泡都从单元格中流出。
This is the code that lead to this:这是导致此的代码:
let imageView = UIImageView()
let width = self.frame.width
let height = self.frame.height
let img_width = height //* 0.8
let img_height = height
let y = (height - img_height)/2
let x = width*0.05
imageView.frame = CGRect(
x: x
, y: CGFloat(y)
, width: img_width
, height: img_height
)
let rounded = imageView
.makeRounded()
.border(width:1.0, color:Color.white.cgColor)
self.addSubview(rounded)
The imageView
extension functions are: imageView
扩展功能为:
func makeRounded() -> UIImageView {
self.layer.borderWidth = 0.5
self.layer.masksToBounds = false
self.layer.borderColor = Color.white.cgColor
self.layer.cornerRadius = self.frame.width/2
self.clipsToBounds = true
// see https://developer.apple.com/documentation/uikit/uiview/contentmode
self.contentMode = .scaleAspectFill
return self
}
func border( width: CGFloat, color: CGColor ) -> UIImageView{
self.layer.borderWidth = width
self.layer.borderColor = color
return self
}
Which is very vanilla.这是非常香草。
This is odd because I laid out the textview vertically in the exact same way, that is: (parentHeight - childHeight)/2
, and it is centered.这很奇怪,因为我以完全相同的方式垂直布置了 textview,即:
(parentHeight - childHeight)/2
,并且它居中。 You can see it in the blue text boxes in cell two and three.您可以在单元格 2 和 3 的蓝色文本框中看到它。
____ EDIT _______ ____ 编辑 _______
This is how I laid out the cell这就是我布置单元格的方式
let data = dataSource[ row - self._data_source_off_set ]
let cell = tableView.dequeueReusableCell(withIdentifier: "OneUserCell", for: indexPath) as! OneUserCell
// give uuid and set delegate
cell.uuid = data.uuid
cell.delegate = self
// render style: this must be set
cell.hasFooter = false //true
cell.imageSource = data
cell.headerTextSource = data
cell.footerTextSource = data
// color schemes
cell.backgroundColor = Color.offWhiteLight
cell.selectionColor = Color.graySecondary
Add these constraints to you imageView and remove frame and its calculations将这些约束添加到您 imageView 并删除框架及其计算
self.contentView.addSubview(rounded)
self.mimageView.translatesAutoresizingMaskIntoConstraints = false
self.mimageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor,constant: 20).isActive = true
self.mimageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
self.mimageView.heightAnchor.constraint(equalTo: contentView.heightAnchor).isActive = true
self.mimageView.widthAnchor.constraint(equalTo: contentView.heightAnchor).isActive = true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.