简体   繁体   中英

Swift - changing image view background image via segmented control

The title itself explains as much as i will be able to. Basically, i have a segmented control that i want to change the image within my image view after each segment is selected, but i can't seem to apply or find the logic to resolve my problem. The answer itself is probably very simple, but i'm really new to Swift and didn't manage to find an answer anywhere, so i would love a solution to my problem. Thanks!

@IBOutlet weak var newImageView: UIImageView!

@IBAction func chooseImage(sender: AnyObject) {
    if myPhotoSegment.selectedSegmentIndex == 0
    {

        newImageView = UIImage(named: "3.jpg")


    }


    if myPhotoSegment.selectedSegmentIndex == 1
    {


    }

You can't set the value of a UIImageView to a UIImage. Set the value of newImageView.image instead. This is also a good opportunity for a switch statement.

@IBAction func chooseImage(sender: AnyObject) {
    switch myPhotoSegment.selectedSegmentIndex {
    case 0:
      newImageView.image = UIImage(named: "3.jpg")
    case 1:
      newImageView.image = UIImage(named: "4.jpg")
    default:
      newImageView.image = nil
    }
}

Segment using image in imageview in swift4

@IBOutlet weak var bgimage: UIImageView!


override func viewDidLoad() {
    super.viewDidLoad()
   
    self.view.backgroundColor = UIColor.red
    
    let itemsimg = ["google", "facebook", "instagram" , "twitter"]
    let customSI = UISegmentedControl(items: itemsimg)
    customSI.selectedSegmentIndex = 0
    
    customSI.frame = CGRect(x:50, y:100, width:300, height: 40)
    
    customSI.layer.cornerRadius = 5.0
    customSI.backgroundColor = UIColor.black
    customSI.tintColor = UIColor.white
    
    customSI.addTarget(self, action: #selector(changeimg),for: .valueChanged)
    
    self.view.addSubview(customSI)
}

@objc func changeimg(sender: UISegmentedControl) {
    switch sender.selectedSegmentIndex {
    case 1:
        bgimage.image = UIImage(named: "facebook")
    case 2:
        bgimage.image = UIImage(named: "instagram")
    case 3:
        bgimage.image = UIImage(named: "twitter")
    default:
        bgimage.image = UIImage(named: "google")
    }
}

}

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