I created StackView on main.storyboard and my idea was to add some buttons of constant size 40x40 with images on them (that are originally 400x400px but they should scale down to fill that 40x40) and they should stack up like this: (stack view is invisible, but i marked it red on pic,its 170x50 space in the top right where the animals are)
so in short: all buttons(with pictures of animals) should be same size 40x40 and populated to the left(or to the right) with some spacing of like 2px in between them.
In code i wrote this:
func setupIcon(iconNumber:Int) -> UIButton{
myImageButton = UIButton()
myImageButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
myImageButton.addTarget(self, action: #selector(self.pressed), for: .touchUpInside)
myImageButton.isUserInteractionEnabled = false
//myImageButton.backgroundColor = UIColor.gray
let widthConstraint = NSLayoutConstraint(item: myImageButton, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 40)
let heightConstraint = NSLayoutConstraint(item: myImageButton, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 40)
NSLayoutConstraint.activate([widthConstraint, heightConstraint])
switch(iconNumber){
case 0:
myImageButton.setImage(UIImage(named: "hamster")!, for: .normal)
return myImageButton
case 1:
myImageButton.setImage(UIImage(named: "dog")!, for: .normal)
return myImageButton
...
default:
myImageButton.setImage(UIImage(named: "hamster")!, for: .normal)
return myImageButton
}
}
to return UIButton which i then add to my StackView by calling:
cell.iconStackView.addArrangedSubview(setupIcon(iconNumber: pett.pic))
and on my StackView settings I have:
Axis: Horizontal
Alignment: Center
Distribution: Equal Spacing
Content mode: Left
Semantic: Unspecified
but that gives me this kind of behavior of those buttons:
and as you can see there are several problems:
1) the constrains i added no longer work when there is only 1 button present
2) i cannot figure out what should i set my StackView settings to make them all go closer to each other and to the right with rest of the space to the left blank
can you help me out what to do to get my desired effect on these buttons? Thanks.
note: every cell with those numbers "13:00" etc have different number of buttons present. My goal is to have all animals to the right, no matter if 1 or 3-4. Images shouldn't stretch like the dog, or be spaced like those 2 in the second or third row