在imageView的中心添加标签

时间:2018-10-08 22:44:07

标签: swift

我有两个图像,就像问题末尾的图片一样(列表和红点的图像)。我想在红点的中心添加一个标签。这是我的代码不起作用:

image = UIImageView(image: UIImage(named: "pallino"))
image.frame = CGRect(x: 55, y: self.view.frame.height-60, width: 22, height: 22)
self.view.addSubview(image)
image.layer.cornerRadius = image.frame.width/2
label = UILabel(frame: CGRect(x: self.image.center.x, y: self.image.center.y, width: image.frame.size.width, height: image.frame.size.height))
label.text = "4"
label.font = UIFont(name:"HelveticaNeue-Bold", size: 15.0)
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = UIColor.black
image.addSubview(label)

有人可以告诉我我错了吗?

enter image description here

2 个答案:

答案 0 :(得分:2)

此行中的问题:

label = UILabel(frame: CGRect(x: self.image.center.x, y: self.image.center.y, width: image.frame.size.width, height: image.frame.size.height))

self.image.center.x -The center point is specified in points in the coordinate system of its superview,这意味着 self.image.center 不是 image的中心

您需要标签框架,像这样:

let imageSize = 22
let frame = CGRect(x: 0, y: 0, width: imageSize, height: imageSize)
let label = UILabel(frame: frame)
label.aligment = .center

答案 1 :(得分:0)

您可以在标签中设置约束(水平居中和垂直居中)。尝试使用以下代码。

let label = UILabel()
label.text = "4"
label.font = UIFont(name:"HelveticaNeue-Bold", size: 15.0)
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = UIColor.black
image.addSubview(label)
label.centerXAnchor.constraint(equalTo: self.image.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: self.image.centerYAnchor).isActive = true