Reputation: 840
This is weird and I've tried different permutations of UIControl.State(). Unless I put in a background color to the image, the actual image doesn't change.
func followUserLocation {
let button = UIButton(type: UIButton.ButtonType.custom)
button.frame = CGRect(x: 10, y: 500, width: 50, height: 50)
if followUserStatus {
followUserButton = UIImage(named: "follow_user_high")
button.setImage(followUserButton, for: .normal)
let coordinateRegion = MKCoordinateRegion(center: coordinatesToAppend, latitudinalMeters: 2500, longitudinalMeters: 2500)
vcTrainMapView.setRegion(coordinateRegion, animated: true)
print("0 AA - TRUE \(followUserButton) \(UIControl.State())")
} else {
followUserButton = (UIImage(named: "follow_user"))
button.setImage(followUserButton, for:.selected)
print("0 BB- FALSE \(followUserButton) \(UIControl.State())")
}
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
// button.backgroundColor = .lightGray // Once I utilise this, it works.
self.view.addSubview(button)
}
Here's the print out put. The UIControl.State() also does not change when pressed.
0 AA - TRUE Optional(<UIImage:0x60000154b0f0 named(main: follow_user_high) {40, 40}>) UIControlState(rawValue: 0)
0 AA - TRUE Optional(<UIImage:0x60000154b0f0 named(main: follow_user_high) {40, 40}>) UIControlState(rawValue: 0)
0 BB- FALSE Optional(<UIImage:0x600001504a20 named(main: follow_user) {40, 40}>) UIControlState(rawValue: 0)
0 BB- FALSE Optional(<UIImage:0x600001504a20 named(main: follow_user) {40, 40}>) UIControlState(rawValue: 0)
0 AA - TRUE Optional(<UIImage:0x60000154b0f0 named(main: follow_user_high) {40, 40}>) UIControlState(rawValue: 0)
0 AA - TRUE Optional(<UIImage:0x60000154b0f0 named(main: follow_user_high) {40, 40}>) UIControlState(rawValue: 0)
0 AA - TRUE Optional(<UIImage:0x60000154b0f0 named(main: follow_user_high) {40, 40}>) UIControlState(rawValue: 0)
Upvotes: 0
Views: 110
Reputation: 8866
I think you should remove if statement then set your button image on both .normal
and .selected
states. After that, update the button selection state.
func followUserLocation {
let button = UIButton(type: UIButton.ButtonType.custom)
button.frame = CGRect(x: 10, y: 500, width: 50, height: 50)
followUserButton = UIImage(named: "follow_user_high")
button.setImage(followUserButton, for:.selected)
followUserButton = (UIImage(named: "follow_user"))
button.setImage(followUserButton, for: .normal)
if followUserStatus {
let coordinateRegion = MKCoordinateRegion(center: coordinatesToAppend, latitudinalMeters: 2500, longitudinalMeters: 2500)
vcTrainMapView.setRegion(coordinateRegion, animated: true)
}
button.addTarget(self, action: #selector(buttonAction(_:)), for: .touchUpInside)
self.view.addSubview(button)
}
@objc private func buttonAction(_ sender: UIButton) {
sender.isSelected.toggle()
print(sender.isSelected)
}
Upvotes: 2