Hacking Bear Hacking Bear - 1 year ago 79
Swift Question

iOS adding image view at center programmatically

I attempt to create a button panel with 3 buttons in two rows. Given it does not need to be flexible, I tried

class MyViewController : UIViewController {
@IBOutlet weak var buttonPanel: UIView! // auto layout, aligned to the bottom of screen
var icon0: UIImageView!
var icon1: UIImageView!
var icon5: UIImageView!

override func viewDidLoad() {
icon0 = UIImageView(image: UIImage(named: "ic_smiley_gray.png"))
icon1 = UIImageView(image: UIImage(named: "ic_smiley_gray.png"))
// ...
icon5 = UIImageView(image: UIImage(named: "ic_smiley_gray.png"))
let icons = [icon0, icon1, ..., icon5]

let btnCellW = CGFloat(self.view.bounds.width) / 3.0
let btnCellH = buttonPanel.frame.height / 2.0
for j in 0..<2 {
for i in 0..<3 {
let rect = CGRect(x: btnCellW * CGFloat(i),
y: btnCellH * CGFloat(j),
width: btnCellW, height: btnCellH)
let cell = UIView(frame: rect)
cell.layer.borderWidth = 0.5
cell.layer.borderColor = UIColor.grayColor().CGColor
cell.layer.backgroundColor = UIColor(red: 0.85 + 0.15 * CGFloat(1 - i % 2), green: 0.85, blue: 0.85,
alpha: 1.0).CGColor
let ic = icons[i + j*3]
ic.center = cell.center
ic.layer.borderWidth = 0.5
ic.layer.borderColor = UIColor.brownColor().CGColor
NSLog("adding icon \(ic.image) at \(ic.center.x) x \(ic.center.y)")

The button panel is drawn correctly with the cells, but only the first cell has an image, so the image asset is good. Other cells are blank. What is my problem?

enter image description here


The problem is this line:

ic.center = cell.center

That can't possibly be right, because the center of a view is in the coordinates of its superview. You are mixing apples and oranges. You want the center of ic to be centered within its superview, but instead you are putting it at the same coordinates relative to cell that cell has relative to buttonPanel! Thus, all the ic images except the first are _outside the boundsof theircell`, and are thus invisible.

Instead, figure out the center of cell bounds and put the center of ic there: i.e., at CGPoint(x:cell.bounds.width/2, y:cell.bounds.height/2).