2017-02-23 71 views
1

我想在imageView的底部添加一個標籤作爲子視圖,但當圖像更改其高度或寬度時,標籤無法響應。 所以我想製作一個動態標籤。如何以編程方式在imageView底部添加標籤?

This is what i did until now

+0

你使用自動佈局,否則 –

+0

@ Anbu.Karthik不,我沒有使用autolayout,我試圖通過向標籤添加框架來編程。 –

回答

0

這裏例如添加標籤,以圖像的

let picImage:UIImageView = { 
    let imageView = UIImageView() 
    let image = UIImage(named: "test") 
    imageView.image = image 
    imageView.contentMode = .scaleAspectFill 
    imageView.translatesAutoresizingMaskIntoConstraints = false 
    return imageView 
    }() 
let durationLabel: UILabel = { 
    let label = UILabel() 
    label.text = "1:20:12" 
    label.font = UIFont(name:"HelveticaNeue-Bold", size: 15.0) 
    label.textAlignment = NSTextAlignment.right 
    label.numberOfLines = 1 
    label.textColor = UIColor.white 
    label.translatesAutoresizingMaskIntoConstraints = false 
    return label 
}() 
func setupView(){ 
// I will skip part of image setup 
self.picImage.addSubview(durationLabel) 
    durationLabel.bottomAnchor.constraint(equalTo: picImage.bottomAnchor).isActive = true 
    durationLabel.leftAnchor.constraint(equalTo: picImage.leftAnchor, constant: 5).isActive = true 
     durationLabel.rightAnchor.constraint(equalTo: picImage.rightAnchor, constant: -5).isActive = true 
} 

這段代碼添加標籤到設置約束下的圖像和左右

https://i.stack.imgur.com/wGIZy.png

+0

謝謝,它的工作原理。 –

1

添加像

var lbl1 = UILabel(frame: CGRect(x: yourimageview.frame.origin.x, y: yourimageview.frame.origin.y + yourimageview.frame.size.height + 5, width: yourimageview.frame.size.width, height: asyourWish)) 


lbl1.textColor = UIColor.black 
lbl1.frame = position 
lbl1.backgroundColor = UIColor.clear 
lbl1.textColor = UIColor.white 

lbl1.text = "TEST" 
self.view.addSubview(lbl1) 
+0

你需要與此有關的幫助嗎 –

相關問題