简体   繁体   中英

How to adjust UIImageView margin programmatically with Swift

I have a UIImageView as part of a UICollectionViewCell that I would like to use to visually display a quantity (like a progress bar). In this case the ImageView and its offset represent the percentage remaining of a given item represented by the cell.

Imagine an image of water inside a glass. When the glass is full you see all of the water texture. When the glass is half full, you see half of the water image. so on and so forth...

I want to adjust the top margin of the ImageView based on the percentage remaining. for example:

var image : UIImageView
var item = inventoriedItem(percentageRemaining : 100)

var pctLeft = item.percentageRemaining
pctLeft = 42

// PSEUDOCODE:
image.topMarginOffset = 100 - pctLeft

You could try adjusting the frame of the UIImageView based on the percentage left.

var image = UIImageView(frame: CGRect(x: 20, y: 10, width: 50, height: 100))
var pctLeft = 0.42

//assuming you want a vertical progress bar (like a glass of water).
image.frame = CGRect(x: 20, y: 10 + (100 * (1 - pctLeft)), width: 50, height: 100 * pctLeft)

Here I programmatically push the Y value down based on the reduced size of the bar. Let me know if this is what you were looking for...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM