以编程方式在父视图内垂直居中放置图像(y轴)

问题描述 投票:0回答:1

我正在使用Swift 5。

目标是将UIImageView垂直放置在视图内部。目前看起来像enter image description here

请注意,所有图像气泡都已从单元格中流出。

这是导致此的代码:

    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)

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

}

非常香草。

这很奇怪,因为我以完全相同的方式垂直放置了文本视图,即:(parentHeight - childHeight)/2,并且居中。您可以在第二和第三单元格的蓝色文本框中看到它。

____编辑_______

这是我布置单元格的方式

        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
ios swift uikit
1个回答
0
投票

将这些约束添加到您的imageView并删除框架及其计算方法

self.contentView.addSubview(rounded)
   rounded.translatesAutoresizingMaskIntoConstraints = false
   rounded.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
   rounded.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
   rounded.heightAnchor.constraint(equalTo: contentView.heightAnchor, multiplier: 1, constant: 0).isActive = true
   rounded.widthAnchor.constraint(equalTo: contentView.heightAnchor, multiplier: 1, constant: 0).isActive = true
© www.soinside.com 2019 - 2024. All rights reserved.