UISegmentedControl if statement - ios

I am trying learning the UISegmentedControl and want to figure out how to get it to work within an if statement to return one value based on selection and another value based on the other selection. There is only two values the UISegment can return - "Fixed" or "Varibale". The code below does not work but gives an idea what I want. The two variables are predefined.
#IBAction func calPenalty(_ sender: UIButton) {
let startDate = termStartDate.text
let mortgageTerm = Double(mortgageTermLabel.text!)
let discount = Double(mortgageDiscountLabel.text!)
let mtgCashback = Double(casbackRecieved.text!)
let mtgBalance = Double(mortgageBalance.text!)
let rate = Double(currentRate.text!)
//let mortgageType = mortgageType
let lender = Global.selectedRate
if let oneYear = Double((lender?.oneYear)!),
let twoYear = Double((lender?.twoYear)!),
let threeYear = Double((lender?.threeYear)!),
let fourYear = Double((lender?.fourYear)!),
let fiveYear = Double((lender?.fiveYear)!) {
let maturityDate = (getMaturityDate(startdate: startDate!, termMonths: Int(mortgageTerm!)))
let monthsToMaturity = daysBetweenDates(endDate: maturityDate)/365*12
let comparisonTerm = (IRDComparisonTerm(monthsToMaturity: monthsToMaturity))
let cashback = cashbackRepayment(cashbackRecieved: mtgCashback!, mtgTerm: Double(mortgageTerm!), mthsToMaturity: Double(monthsToMaturity))
print(cashback)
var comparisonRate: Double = 0
switch comparisonTerm
{
case 12:
comparisonRate = oneYear
case 24:
comparisonRate = twoYear
case 36:
comparisonRate = threeYear
case 48:
comparisonRate = fourYear
case 60:
comparisonRate = fiveYear
default:
comparisonRate = 0
} // end switch statement
print(comparisonRate)
let IRD = IRDPenalty(IRDComparisonRate: comparisonRate, mtgBalance: mtgBalance!, mthsToMaturity: Double(monthsToMaturity), discount: discount!, currentRate: rate!)
let threeMthsInterestPenalty = threeMonthsInterestPenalty(mtgBalance: mtgBalance!, mtgRate: rate!)
print (IRD)
print (threeMthsInterestPenalty)
var penalty: Double = 0
// var totalPenalty: Double = 0
if IRD > threeMthsInterestPenalty {
penalty = IRD + cashback
}else{
penalty = threeMthsInterestPenalty + cashback
}
// totalPenalty = penalty + cashback
calculationLabel.text = String(penalty)
}
}
// triggers result based on value selected
#IBAction func valueChanged(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
calculationLabel.text = String(penalty)
case 1:
calculationLabel.text = String(threeMthsInterestPenalty + cashback)
default:
calculationLabel.text = String(penalty)
}
}
Edit: I am still working on this problem. I have updated to the above code to show all the code within the IBAction. The #IBAction does not work as the variables are undefined based on where they are posted within the code. The Storyboard has a UIsegmentedControl with to values "Fixed and Variable. If the user selects fixed then I want it to show as per the IBAction for UISegement Control.

If what you want is to check when the value of your segmented control changes, and you want to do it programmatically, you firstly need to register a target-action method using valueChanged constant. Then, write up your valueChanged function. Check this out for more information.
import UIKit
class ViewController: UIViewController {
// Reference from Storyboard or Interface Builder
#IBOutlet weak var mortgageType: UISegmentedControl!
// For set up a UISegmentedControl programmatically
var segmentedControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
}
override func loadView() {
super.loadView()
// Programmatically setup
let items = ["Cinnamon", "Clove"]
segmentedControl = UISegmentedControl(items: items)
segmentedControl.selectedSegmentIndex = 0
segmentedControl.frame = CGRect(x: 120, y: 200, width: 200, height: 30)
segmentedControl.tintColor = UIColor.black
segmentedControl.addTarget(self, action: #selector(self.valueChanged(_:)), for: .valueChanged)
self.view.addSubview(segmentedControl)
}
#IBAction func valueChanged(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
print("Hi")
case 1:
print("Bye")
default:
print("Nothing")
}
}
}
If you reference your UISegmentedControl from Storyboard and Interface Builder. You should also add an action to it.
Update to the edited question
#IBAction func calPenalty(_ sender: UIButton) {
if mortgageType.selectedSegmentIndex == 0 {
print("Fixed")
} else {
print("Variable")
}
}

Related

Quiz app option button background color change

When we click on the wrong option in the quiz application, the background color is red and the background color of the correct option is green. how can I do that? My model :
struct QuizModel {
let q : String
let a : [String]
let correctAnswer : Int
}
my question :
QuizModel(q: "Aşağıdakilerden hangisi ilk yardımın amaçlarından biri değildir?", a: [
"A) İlaçla tedavi etmek","B) Durumun kötüleşmesini önlemek","C) Hayati tehlikeyi ortadan kaldırmak","D) Yaşamsal fonksiyonların sürdürülmesini sağlamak"], correctAnswer: 0)
answer func :
func checkAnswer(userAnswer : Int)-> Bool {
if userAnswer == quiz[questionNumber ].correctAnswer {
return true
}else{
return false
}
}
user tapped option button :
#objc func TappedButton(_ sender : UIButton){
let userAnswer = sender.tag
let userRightGot = quizBrains.checkAnswer(userAnswer: userAnswer)
if userRightGot {
sender.backgroundColor = .green
score += 1
scoreLabel.text = "\(score)"
}else{
sender.backgroundColor = .red
failScore += 1
failScoreLabel.text = "\(failScore)"
}
The method affects only the currently tapped button, you have to update the state of the other buttons, too.
Something like this, button0-button3 are the references to the buttons, you have to add IBOutlets if there are none.
var buttons = [button0, button1, button2, button3]
// please name methods with starting lowercase letter
#objc func tappedButton(_ sender : UIButton) {
let userAnswer = sender.tag
let correctAnswer = quiz[questionNumber].correctAnswer
for button in buttons {
button.backgroundColor = button.tag == correctAnswer ? .green : .red
}
if userAnswer == correctAnswer {
score += 1
scoreLabel.text = "\(score)"
} else {
failScore += 1
failScoreLabel.text = "\(failScore)"
}
}

how would I know what button to place the selected content of the dropdown box in. Swift

I am using this dropdown box in my project: https://github.com/kirkbyo/Dropper
I want to enter the selected item from the drop-down box into the text of the button. However, I have 3 buttons which all with drop down boxes and to find out what item has been pressed you use the func DropperSelectedRow(_ path: IndexPath, contents: String) method which will give you the index path and string of what was clicked. in which case you just place the content into the button text but I don't know which button to place it in. How would I find this out?
this is my code:
class ListComposerTableViewController: UITableViewController, UITextViewDelegate, DropperDelegate {
#IBOutlet weak var typeButton: UIButton!
#IBOutlet weak var dateButton: UIButton!
#IBOutlet weak var publicButton: UIButton!
let typeDropper = Dropper(width: 105, height: 105)
let typeOptions = ["Event", "Birthday", "Christmas", "Charity"]
let publicDropper = Dropper(width: 105, height: 105)
let publicOptions = ["Public", "Private"]
let dueDropper = Dropper(width: 105, height: 130)
let dueOptions = ["Bithday", "Christmas", "Custom Date"]
override func viewDidLoad() {
super.viewDidLoad()
//set up the droppers
typeDropper.items = typeOptions // Item displayed
typeDropper.maxHeight = 105
typeDropper.theme = Dropper.Themes.black(UIColor.white)
typeDropper.delegate = self
typeDropper.cornerRadius = typeButton.layer.cornerRadius
typeDropper.cellColor = Colours.flatColour.main.headings
typeDropper.cellBackgroundColor = UIColor.white
typeDropper.width = 105
typeDropper.height = 105
publicDropper.items = publicOptions // Item displayed
publicDropper.maxHeight = 105
publicDropper.theme = Dropper.Themes.black(UIColor.white)
publicDropper.delegate = self
publicDropper.cornerRadius = publicButton.layer.cornerRadius
publicDropper.cellColor = Colours.flatColour.main.headings
publicDropper.cellBackgroundColor = UIColor.white
publicDropper.width = 105
publicDropper.height = 105
dueDropper.items = dueOptions // Item displayed
dueDropper.maxHeight = 130
dueDropper.theme = Dropper.Themes.black(UIColor.white)
dueDropper.delegate = self
dueDropper.cornerRadius = publicButton.layer.cornerRadius
dueDropper.cellColor = Colours.flatColour.main.headings
dueDropper.cellBackgroundColor = UIColor.white
dueDropper.width = 105
dueDropper.height = 105
}
#IBAction func typeDidPress(_ sender: Any) {
if typeDropper.status == .hidden {
typeDropper.showWithAnimation(0.15, options: Dropper.Alignment.center, button: typeButton)
} else {
typeDropper.hideWithAnimation(0.1)
}
}
#IBAction func dueDidPress(_ sender: Any) {
if dueDropper.status == .hidden {
dueDropper.showWithAnimation(0.15, options: Dropper.Alignment.center, button: dateButton)
} else {
dueDropper.hideWithAnimation(0.1)
}
}
#IBAction func publicDidPress(_ sender: Any) {
if publicDropper.status == .hidden {
publicDropper.showWithAnimation(0.15, options: Dropper.Alignment.center, button: publicButton)
} else {
publicDropper.hideWithAnimation(0.1)
}
}
func DropperSelectedRow(_ path: IndexPath, contents: String) {
print(path)
print(contents)
}
How would I place the contents of what was clicked into the button text of where the dropper came from? Thank you.
Use func DropperSelectedRow(_ path: IndexPath, contents: String, tag: Int) instead.
You can assign a tag for your buttons and check this property when delegate method is invoked.
For example: typeDropper.tag = 1
And
func DropperSelectedRow(_ path: IndexPath, contents: String, tag: Int) {
if tag == 1 {
typeButton.setTitle(contents, for: .normal)
}
}

onClick event in a for loop (Swift) not working

Data sharing between two view controllers by using segue is not working in for loop. I am using Xcode9 and Swift
swift4
ViewController.swift
import UIKit
import SwiftyJSON
import Alamofire
class ViewController: UIViewController {
var distnames = [String]()
var distcodes = [String]()
var data1: [AnyObject] = []
var values = [String]()
var values1 = [String]()
var current_arr :[String] = []
var ofcnames = " ";
var ofccodes = " ";
var code = " ";
var testtext = "";
var id = "";
var tiTle = "";
var releaseYear = "";
#IBOutlet weak var Verticalstackview: UIStackView!
#IBOutlet weak var scrollview: UIScrollView!
#IBOutlet weak var testlabel: UILabel!
#IBOutlet weak var mainView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
print("code is \(code)")
self.values = [String]()
self.values1 = [String]()
self.ofcnames = "";
self.ofccodes = "";
Alamofire.request("https://facebook.github.io/react-native/movies.json")
.responseJSON { (response) in
if ((response.result.value) != nil) {
let jsondata = JSON(response.result.value!)
// print(jsondata)
if let da = jsondata["movies"].arrayObject
{
self.data1 = da as [AnyObject]
print("resp is \(da) ")
}
print("respcode count is \(self.data1.count) ")
self.Verticalstackview.height(constant: 40)
self.mainView.height(constant: CGFloat(40 * self.data1.count))
self.scrollview.height(constant: CGFloat(40 * self.data1.count))
for distics in self.data1 {
if let resp = distics as? NSDictionary {
self.id = resp["id"] as! String
self.tiTle = resp["title"] as! String
self.releaseYear = resp["releaseYear"] as! String
let stackView = UIStackView()
stackView.height(constant: 40)
stackView.distribution = .fill
stackView.alignment = .fill
stackView.axis = .horizontal
stackView.spacing = 5
let lblId = UILabel()
lblId .text = "\(self.id)"
lblId .font = UIFont(name: "verdana", size: 15.0)
lblId .textAlignment = .center
lblId .textColor = .gray
lblId .numberOfLines = 0
lblId .width(constant: 55)
let lbltiTle = UILabel()
lbltiTle.text = "\(self.tiTle)"
lbltiTle.font = UIFont(name: "verdana", size: 15.0)
lbltiTle.textAlignment = .left
lbltiTle.textColor = .black
lbltiTle.numberOfLines = 0
lbltiTle.width(constant: 120)
let tap = UITapGestureRecognizer.init(target:self,action: #selector(self.tapFunction) )
lbltiTle.isUserInteractionEnabled = true
lbltiTle.addGestureRecognizer(tap)
self.testtext = lbltiTle.text!
let lblRYear = UILabel()
lblRYear.text = "\(self.releaseYear)"
lblRYear.font = UIFont(name: "verdana", size: 15.0)
lblRYear.textAlignment = .right
lblRYear.textColor = .black
lblRYear.numberOfLines = 0
lblRYear.width(constant: 100)
stackView.addArrangedSubview(lblId )
stackView.addArrangedSubview(lbltiTle)
stackView.addArrangedSubview(lblRYear)
self.Verticalstackview.addArrangedSubview(stackView)
}
}
}
print(self.values1)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#objc func tapFunction(sender:UITapGestureRecognizer) {
print("tap working")
self.performSegue(withIdentifier: "Segue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let secondcntroller = segue.destination as! SecondViewController
secondcntroller.mystring = self.testtext
}
}
extension UIView{
func height(constant : CGFloat){
setConstraint(value: constant,attribute: .height)
}
func width(constant : CGFloat){
setConstraint(value: constant,attribute: .width)
}
private func removeConstraint(attribute: NSLayoutAttribute){
constraints.forEach {
if $0.firstAttribute == attribute
{
removeConstraint($0)
}
}
}
private func setConstraint(value:CGFloat ,attribute: NSLayoutAttribute){
removeConstraint(attribute: attribute)
let Constraint =
NSLayoutConstraint(item: self,
attribute: attribute,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: value)
self.addConstraint(Constraint)
}
}
SecondViewController.swift
import UIKit
class SecondViewController: UIViewController {
#IBOutlet weak var label: UILabel!
var mystring = String()
override func viewDidLoad() {
super.viewDidLoad()
label.text=mystring
}
}
When I click the movie name text, I want that to be displayed on the second view using segue.
https://i.stack.imgur.com/dvm8j.png
But always it displays the last movie name. Please assist me sorting this issue.
https://i.stack.imgur.com/UqyqM.png
You should update your tapFunction
#objc func tapFunction(sender:UITapGestureRecognizer) {
let touchedLabel = sender.view as! UILabel
self.testtext = touchedLabel.text
self.performSegue(withIdentifier: "Segue", sender: self)
}
Hope it helps
EDIT
Now as you wants to pass the multiple values, what you can do is:
First change your for in loop from
for distics in self.data1 {
To
for (index, distics) in self.data1.enumerated() {
Now, set the tag to your label below this line
lbltiTle.addGestureRecognizer(tap)
// Add tag to your label
lbltiTle.tag = index
//**TIP: You should name the variables in camelCase format**
Now modify your function, that detects the tap on label and get the object with index being passed with the label in form of it's tag. Modify it to.
#objc func tapFunction(sender:UITapGestureRecognizer) {
let touchedLabel = sender.view as! UILabel
let touchedIndex = touchedLabel.tag
let selectedDict: NSDictionary = self.data1[touchedIndex]
print("selectedDict:\(selectedDict)")
self.performSegue(withIdentifier: "Segue", sender: self)
}
You can print the required values from it.
NOTE: For the pure swift approach, you should Avoid using NSDictionary, better use [String: Any] which is a key value pair.
Hope it helps
The self.testtext property from ViewController is not set properly. It should be set every time the tapFunction() is called.
Any way I recomand you to use UITabiewViewController and a data source array which should hold all your elements to display.
Issue
That is because you are passing testtext as a parameter to the next ViewController.mystring. testtext is being changed every time on the loop and the last time it is being changed it is on the last element. Therefore you need to save an index to know where you pressed.
Solution
Change your for loop to get the index of the element you're iterating as above
for index in 0..<self.data1.count {
let distics = self.data1[index]
// Other lines of code
lbltiTle.tag = index
}
Change your handler as below
#objc func tapFunction(sender:UITapGestureRecognizer) {
print("tap working")
guard let index = sender.view?.tag,
let title = (self.data1[index] as? NSDictionary)["title"] else { return }
testtext = title
self.performSegue(withIdentifier: "Segue", sender: self)
}
Add one more function for your label.
lbltiTle.target(forAction: onClickLabel, withSender:)
Definition -
func onClickLabel(sender: UILabel) {
self.testtext = sender.text
}
Call this in your tap function

Incorrect height of tableview cell XIB in UITableView for first time?

I am having hard time resolving one issue. I have a tableview which has many prototype cells. One of them i am using a tagview to show multiple tags selected. So i have used a XIB file which has a TAGVIEW as subview of it & I have used that XIB in tableview cell. Now when i first load the tableview and scroll down then height of cell is large but when i scroll down and up then it's fits in the size of tags. I have tried below solutions for the but not of them worked.
I tried solutions:
1.cell.layoutIfNeeded before return cell.
2.cell.layoutSubView
3.cell.tagView.layoutIfNeeded
4.cell.setNeedsLayout()
5.Relaod tableview in ViewDidAppear
6.In tagViewCellXIB, in AwakeForNib method added self.layoutIfNeeded.
7.In tagViewCellXIB,Override didMoveToParent() & added self.layoutIfNeeded.
I have given estimated row height already.
Here is tagViewCell Class
class TagViewCell: UITableViewCell {
#IBOutlet weak var tagView: TagListView!
#IBOutlet weak var textfield: UITextField!
#IBOutlet weak var titleLbl: UILabel!
#IBOutlet weak var heightTagViewConstraint : NSLayoutConstraint!
#IBOutlet weak var lblValidation: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.layoutIfNeeded()
// Initialization code
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
self.layoutIfNeeded()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
self.heightTagViewConstraint.constant = 35
}
func configureView(type: TagCellType){
switch type {
case .Language:
setupLanguageCell()
titleLbl.text = "Language"
textfield.isHidden = true
if UserData.userData.language.count == 0{
tagView.isHidden = true
textfield.isHidden = false
textfield.placeholder = "What languages do you speak?"
}
break
default:
textfield.isHidden = true
setupTagCell(tagType: type)
if type == .preferArea {
seUpPreffredAreaValidation()
titleLbl.text = "Preferred areas"
if UserData.userData.preferAreaArr.count == 0{
tagView.isHidden = true
textfield.isHidden = false
textfield.placeholder = "What areas do you prefer?"
}
}
else if type == .City{
titleLbl.text = "Preferred cities"
if UserData.userData.cities.count == 0{
tagView.isHidden = true
textfield.isHidden = false
textfield.placeholder = "What city do you prefer? (Optional)"
}
}else{
titleLbl.text = "Preferred countries"
if UserData.userData.country.count == 0{
tagView.isHidden = true
textfield.isHidden = false
textfield.placeholder = "What country do you prefer? (Optional)"
}
}
break
}
}
/// Set up tag view
func setupLanguageCell() {
tagView.removeAllTags()
tagView.tag = 1003 // For Language field
for (index, elememt) in UserData.userData.language.enumerated() {
print(index)
if let langDict = elememt as? NSDictionary{
tagView.isHidden = false
let languageTagView = tagView.addTag(langDict.value(forKey: "lang_name") as! String)
languageTagView.tagBackgroundColor = UIColor.clear
languageTagView.textColor = .black
languageTagView.textFont = UIFont.systemFont(ofSize: 17)
languageTagView.paddingX = -1
languageTagView.isUserInteractionEnabled = false
let levelTagView = tagView.addTag(Constants.languageLevel[langDict.value(forKey: "level") as! Int])
levelTagView.frame = CGRect(x: levelTagView.frame.origin.x, y: (languageTagView.frame.height / 2) - (levelTagView.frame.height / 2) + 2, width: levelTagView.frame.width, height: levelTagView.frame.height)
levelTagView.layoutIfNeeded()
levelTagView.layoutSubviews()
levelTagView.tagBackgroundColor = UIColor().textOrange()
levelTagView.textFont = UIFont.systemFont(ofSize: 10)
levelTagView.cornerRadius = 6
print("pading yyyyyy \(String(describing: tagView.rowViews.last?.frame.minY))")
if UserData.userData.language.count == index+1{
if (tagView.rowViews.last?.frame.minY)! == 48{
levelTagView.frame.origin.y = (languageTagView.frame.height / 2) - (levelTagView.frame.height / 2) + 8
}
}
}
}
if UserData.userData.language.count == 0 {
self.lblValidation.isHidden = false
} else {
self.lblValidation.isHidden = true
}
}
func seUpPreffredAreaValidation() {
if UserData.userData.preferAreaArr.count == 0 {
self.lblValidation.isHidden = false
} else {
self.lblValidation.isHidden = true
}
}
/// setup cell for country and cities
///
/// - Parameter tagType: type of cell country or cities
func setupTagCell(tagType:TagCellType) {
tagView.removeAllTags()
var tagArray:[String] = []
tagArray = UserData.userData.country
tagView.tag = 1001 // For countries field
if tagType == .City {
tagArray = []
tagArray = UserData.userData.cities
tagView.tag = 1002 // For city field
}
if tagType == .preferArea {
tagArray = []
tagArray = UserData.userData.preferAreaArr
tagView.tag = 1003
}
var tagValue = ""
for (_, elememt) in tagArray.enumerated() {
tagView.isHidden = false
print(elememt)
if elememt.characters.count > 17 {
let index = elememt.index(elememt.startIndex, offsetBy: 16)
tagValue = elememt.substring(to: index) + ".."
}else{
tagValue = elememt
}
let levelTagView = tagView.addTag(tagValue)
levelTagView.tagBackgroundColor = UIColor().textOrange()
tagView.textFont = UIFont.systemFont(ofSize: 17)
levelTagView.cornerRadius = 8
levelTagView.enableRemoveButton = false
levelTagView.paddingX = 6
levelTagView.paddingY = 3
}
}
}
For cellForRowAtIndexPath below code is used
let cell = self.tableView.dequeueReusableCell(withIdentifier: "tagcell", for: indexPath) as! TagViewCell
cell.configureView(type: .City)
cell.tagView.delegate = self
if UserData.userData.cities.count >= 0 && UserData.userData.cities.count <= 3 {
cell.heightTagViewConstraint.constant = 25.7
}
else if let height = cell.tagView.subviews.last?.frame.maxY {
cell.heightTagViewConstraint.constant = height + 10
}
return cell
Override layoutSubviews in your TagViewCell class like bellow
class TagViewCell: UITableViewCell {
override func layoutSubviews() {
//Set the frame of tagView here
//self.tagView.frame =
}
}
and call cell.layoutIfNeeded while returning cell. If you still get any problem please comment. we are here to help you.

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")
}
}
}

Resources