Modifying images of generated imageViews on button click - ios

I am creating a quiz app and having trouble changing the image which is displayed of a specific imageview that is generated in a for loop.
The following code is responsible for generating the imageviews based on the amount of questions in that specific quiz. It is called in the viewDidLoad() method:
var imageView = UIImageView()
func addProgressImages(to view: UIView, count: Int){
let screenSize = UIScreen.main.bounds.size
for i in 0..<count {
let spacing: CGFloat = 2
let tag = i + 888
let width: CGFloat = screenSize.width/CGFloat(count)
let height: CGFloat = width
if let view = view.viewWithTag(tag){
view.removeFromSuperview()
}
let x = spacing + CGFloat(i) * width
imageView = UIImageView(frame: CGRect(x: x, y: 100, width: width - spacing, height: height))
imageView.image = UIImage(named: "question_progress_empty")
imageView.tag = tag
imageView.contentMode = .scaleAspectFit
view.addSubview(imageView)
//print("imageviews displaying")
}
}
I have made an attempt to change some of the images to another image when the user selects an answer to that question with an if statement:
func changeImage() {
if (optA != questionAns){
imageView.image = UIImage(named: "wrong_answer")
print("opta")
}else if(optB == questionAns){
imageView.image = UIImage(named: "wrong_answer")
print("optb")
}else if(optC == questionAns){
print("optc")
imageView.image = UIImage(named: "wrong_answer")
}else{
print("if statement not initialised")
}
}
https://imgur.com/a/zwJ4EVn - This is the output of the above code
Currently, only the last image will be changed when a user clicks a button.
I need help with modifying the imageview which is related to that specific question, e.g. if question 2 is answered, only that imageview will change while the rest remain unmodified.
Hopefully that explanation made any sense, any input would be appreciated,
Thanks.

See you are doing few things wrong.
you have taken UIImageView as instance variable as below, so after
creating all the images its holding the reference to the last
imageView.
var imageView = UIImageView()
Make the var imageView as local variable and in the func
changeImage() get the proper imageView using its tag value then
try to change its image.
If any doubt plz comment.
How to get the imageView back in changeImage() check below code.
let tag = 888 + (questionNumber - 1)
if let imageView = view.viewWithTag(tag) as? UIImageView {
// Change imageView's image here
}

You will probably want to create an array of image views:
var imageViews = [UIImageView]()
And add your UIImagesViews to that array in your loop:
for i in 0..<count {
var imageView = UIImageView()
// additional setup...
imageViews.append(imageView)
}
Then, you can later iterate over your array and change the images:
for imageView in imageViews {
imageView.image = UIImage(named: "wrong_answer")
// etc.
}

Related

CGRect function is not working while placing image in textfield

I am trying to set image inside the textfield , and for that i am creating an image view in code but when i am trying to adjust its width and height via CGRect(x:int, y:int, width:int, height:int) , its not being applied and the image size is still original. I ve seen so many tutorials for putting image in text field and all of them are using CGRect and its working for them, as size of image gets what they apply in CGRect, but not for me. Below is the code i m trying to use. Image is also attached. Textfield style is rounded (Default) and icon size is 50px.
UIViewController
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var email: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
update()
// Do any additional setup after loading the view.
}
func update() {
email.leftViewMode = .always
let imageview = UIImageView()
let image = UIImage(named: "icon")
imageview.image = image
imageview.frame = CGRect(x: 15, y: 0, width: 50 , height: 50)
email.leftView = imageview
}
}
Also, i ve tried to change 'Render as' to 'template' in image assets but its still not working.
Hey I’ve tried to do it programmatically and it works for me. Quickly drafted it on iPad playgrounds. Try this:
class Test: UIViewController {
let lable = UITextField()
let image = UIImage()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
lable.frame = CGRect(x: 200, y: 200, width: 300 , height: 50)
lable.backgroundColor = .black
update()
self.view.addSubview(lable)
}
func update() {
lable.leftViewMode = .always
let imageview = UIImageView()
let image = UIImage(systemName: "icloud")
imageview.image = image
imageview.frame = CGRect(x: 15, y: 0, width: 50 , height: 50)
lable.leftView = imageview
self.view.addSubview(imageview)
}
}

Give inset to UIImageView before setting Its frame

I have an UITextField component which has an icon on the right side of it. Icon is just an UIImageView. I'm trying to give inset to UIImageView with below code
imageView.image = UIImage(named: "example")?.withAlignmentRectInsets(UIEdgeInsets(top: -4, left: 0, bottom: -4, right: 0))
However, It doesn't work cuz It's frame hasn't been set when setting Its' Image. I'm giving Its frame with below code;
iconImageView.frame = CGRect(
x: bounds.size.width - iconWidth - iconMarginLeft,
y: bounds.size.height - textHeight() - iconMarginBottom,
width: iconWidth,
height: textHeight()
)
and how I setup UIImageView
fileprivate func createIconImageView() {
let iconImageView = UIImageView()
iconImageView.backgroundColor = .clear
iconImageView.contentMode = .scaleAspectFill
iconImageView.autoresizingMask = [.flexibleTopMargin, .flexibleRightMargin]
if (hasToolTip) {
let tapGesture = UITapGestureRecognizer(target: self, action:#selector(toolTipTapped(_:)))
iconImageView.addGestureRecognizer(tapGesture)
iconImageView.isUserInteractionEnabled = true
let image = UIImage(named: "infotooltip")
image?.accessibilityIdentifier = "tooltipImage"
iconImageView.image = image!
changeIconAlphaToOne()
self.iconImageView = iconImageView
} else {
self.iconImageView = iconImageView
changeIconAlphaToZero()
}
addSubview(iconImageView)
}
My problem is that, I need to give UIEdgeInset to the image. However, because I'm trying to give it before setting the frame, It doesn't work. How can I achieve this?
I also try to resize the image by referencing below post but doesn't work for me. I also DO NOT want to put it inside a content view which will make my component class more complicated.
The simplest way to resize an UIImage?

Show UIImage inside UITextfield, tried but doesn't work

I am using xcode8.3 and Swift3 in my project.
I have a UITextField in storyboard, I created a IBOutlet in corresponding controller class:
#IBOutlet weak var myTextField: UITextField!
I would like to show a small image on the right side inside the text field, I found a solution here (though it shows image on left side).
THis is what I tried:
override func viewDidLoad() {
super.viewDidLoad()
let imageView = UIImageView();
let image = UIImage(named: "my_icon");
imageView.image = image;
self.myTextField.rightView = imageView
self.myTextField.rightViewMode = .always
}
(In xcode Assets.xcassets folder I have my_icon.png, my_icon#2x.png, my_icon#3x.png)
When I run the code on iPhone, I don't see my_icon showing anywhere in UITextField. I also tried to add the ".png" suffix when loading image let image = UIImage(named: "my_icon.png");, it doesn't help either.
Why the solution in the link doesn't work for me?
I had similar issue, it sounds funny but it can cause the issue. I believe your imageView's frame is 0.
So
let imageView = UIImageView();
let image = UIImage(named: "my_icon");
imageView.image = image;
imageView.frame = CGRect(x: 0, y: 0, width: imageView.intrinsicContentSize.width, height: imageView.intrinsicContentSize.height)
self.myTextField.rightView = imageView
self.myTextField.rightViewMode = .always
Set frame:
imageView.frame = CGRect(x: 0, y: 0, width: 20, height: 20)

Why is my left view in text field not working?

I've added a left view to my text field using the code below:
usernameField.leftViewMode = UITextFieldViewMode.always
passwordField.leftViewMode = UITextFieldViewMode.always
let usernameImageView = UIImageView()
let usernameImage = UIImage(named: "user icon grey.png")
usernameImageView.image = usernameImage
usernameField.leftView = usernameImageView
let passwordImageView = UIImageView()
let passwordImage = UIImage(named: "lock icon grey.png")
passwordImageView.image = passwordImage
passwordField.leftView = passwordImageView
This didn't work, I then added a UIDesignable, a very neat process that I took from this question below on StackOverflow. This means that I can see the icons in the storyboard, as can be seen below. However, this doesn't show up.
Swift add icon/image in UITextField
The problem is with how you create the image view. You first create an empty image view which then has no size. You then assign the image to the image view but this does not automatically resize the image view.
There are two solutions.
Tell the image view to resize itself after assigning the image.
let usernameImageView = UIImageView()
let usernameImage = UIImage(named: "user icon grey.png")
usernameImageView.image = usernameImage
usernameImageView.sizeToFit()
Create the image view with the image. This is simpler approach.
let usernameImage = UIImage(named: "user icon grey.png")
let usernameImageView = UIImageView(image: usernameImage)
The problem is with your code. using this code now your left view in textField is working.
#IBOutlet weak var name: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
usernameField.leftViewMode = .always
let usernameImageView = UIImageView()
usernameImageView.frame = CGRect(x: 0, y: 0, width: 25, height: 25)
let usernameImage = (your image name)
usernameImageView.image = usernameImage
usernameField.leftView = usernameImageView

Alternative way to show a UIPageControl (Swift)

I'm trying to add an arrow or like an image to correlate to how many view I have in my UIScrollView in swift. Something in line of this
(UPDATE) - My question is how do you insert an image into your scrollview that will tell it to go forward or backwards depending on how many images you have.
Now I know there is the UIPageControl but I'm looking into an alternative way to show that there is a picture and to the right or right and left. This is the code I have so far. I'll try the best I can to explain what I'm doing.
My picSource.count is data from a website that is carrying pictures
I'm multiplying my number of views by the screenwidth
This is an if else statement that shows if a picture is there post bgImage if not post no photoprovided image.
Let me know if you need more information or if I should revise. Thanks!
// Gallery
if (picSource.count > 1){
var picNum:CGFloat = CGFloat(picSource.count)
// UI News Image Scroller
var scroll = UIScrollView(frame:CGRectMake(-5, 650, screenWidth, 260))
scroll.pagingEnabled = true
scroll.showsHorizontalScrollIndicator = false
scroll.showsVerticalScrollIndicator = false
scroll.contentSize = CGSizeMake(picNum*screenWidth, 220)
// Number of views
var numberOfViews = picSource.count
var imageName = ""
// Loop to add views to scroll view
for (var i = 0; i < numberOfViews; i++){
var myIntValue:Int = Int(screenWidth)
var xOrigin = i * myIntValue
// Creates UIImageView instance using myImage
var scrollImageView = UIImageView(frame: CGRect(origin: CGPoint(x: xOrigin, y: 5), size: CGSize(width: screenWidth, height: 250)))
// Tests which image name needs to be used
imageName = picSource[i]
// Creates image object using specified image name "...jpg"
var url = NSURL(string: "http://www/images/cl/" + adID[adCurrentTag] + "/gallery/" + imageName)
var maybeError: NSError?
if var imageData :NSData = NSData(contentsOfURL: url!,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &maybeError) {
var bgImage = UIImage(data:imageData)
scrollImageView.contentMode = .ScaleAspectFit
scrollImageView.image = bgImage
// Adds Image to scroll view
scroll.addSubview(scrollImageView)
}else if let error = maybeError {
var photoNotProvided = UIImage(named:"noPhoto800x800.png")
var photoNotProvidedView = UIImageView(frame: CGRectMake(5, 650.0, screenWidth, 300.0))
scrollImageView.image = photoNotProvided
scroll.addSubview(scrollImageView)
}
}
border.addSubview(scroll)

Resources