I've included the code to my segmented control and UIImageView. Any help would be great, thanks.
let segmentedControl: UISegmentedControl = {
let sc = UISegmentedControl(items: ["Login", "Register"])
sc.translatesAutoresizingMaskIntoConstraints = false
sc.tintColor = UIColor.white
sc.selectedSegmentIndex = 0
sc.addTarget(self, action: #selector(handleSegmentedControlChange), for: .valueChanged)
return sc
}()
// profile pic
lazy var picture: UIImageView = {
var pic = UIImageView()
if segmentedControl.selectedSegmentIndex == 0 {
pic.image = UIImage(named: "Logo")
} else {
pic.image = UIImage(named: "Profile")
let mytapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView))
mytapGestureRecognizer.numberOfTapsRequired = 1
pic.addGestureRecognizer(mytapGestureRecognizer)
pic.isUserInteractionEnabled = true
}
pic.translatesAutoresizingMaskIntoConstraints = false
pic.contentMode = .scaleAspectFill
return pic
}()
The picture is supposed to change and enable the touch gesture but neither of them works.
将If-else块移动到handleSegmentedControlChange选择器。
1) Create a @objc func
that receive as a parameter (_ sender: UISegmentedControl)
, for example:
@objc func segmentedControlChanged(_ sender: UISegmentedControl)
2) After create your UISegmentedControl, use addTarget, like this:
segmentedControl.addTarget(self, action: #selector(segmentedControlChanged(_:)), for: .valueChanged)
3) In the func that you created, implement the corresponding logic:
@objc func segmentedControlChanged(_ sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 0 {
pic.image = UIImage(named: "Logo")
// Also, if you want to resize your image view after set the new image, call sizeToFit() func here.
} else {
pic.image = UIImage(named: "Profile")
// And here.
}
}
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.