I am trying to make an image view set to a certain image when a label displays a certain word from an array which is being randomised.
The picture is supposed to set to the image view when specific words are the text of the label from the array.
Here is the array:
let freeMoodArray = ["Happy", "Sad", "Angry", "Annoyed", "Curious", "Bored", "Chilled", "Furious", "Excited", "Scared", "Emotionless", "Shocked", "Tired", "Sick", "Amused"]
Here is the random label text:"
self.moodAnswer.text = "\(self.freeMoodArray.randomElement()!)"
Now when I load the view, the image chooses a random word from the array which is working. Now, lets say it says Happyas the text of the label.
I want to set a certain image only when it says happy.
Here is my code, which doesn't work: (this func is called in the viewDidLoad())
func emojiMood() {
if moodAnswer.text == "Happy" {
emojiImg.image = UIImage(named: "happy.png")
}
}
how a but a variable and DidSet ?
// create a variable
var moodAnswer : string = "" {
didSet {
// if or switchCase, set image only if the text is equal to Happy
if moodAnswer == "Happy" {
emojiImg.image = UIImage(named: "happy.png")
}
// always set text field with new updated text
self.moodAnswerLabel.text = moodAnswer
}
}
// in your code always set moodAnswer variable, this is more clean and also you set label and image only in a single place
self.moodAnswer = "\(self.freeMoodArray.randomElement()!)"
Related
my problem is I want to put 2 placeholders for one textField. one of the place holders should be on the left and the other should be on the right.
my code:
func returnPlaceHolder(first: String, second: String, textField: UITextField){
let width: Int = Int(textField.bounds.width * 0.2)
let spaceValue = width - (first.count + second.count)
var temp = "\(first) "
let tempCount = spaceValue - (first.count + second.count)
var value = String()
for _ in 0..<tempCount {
temp.append(" ")
}
value = "\(temp) \(second)"
textField.placeholder = value
textField.setLeftPaddingPoints(10)
textField.setRightPaddingPoints(10)
}
I'm currently using this function to create spaces.. but my problem is the spaces won't be the same for more than one textField, and I want them to be aligned..
just like this picture: https://imgur.com/pZZMoNv
and this is the result I'm getting for my current code: https://imgur.com/a/5AN8EXl
don't mind the textFields format & text I can fix them later.. I just want to be able to align the textFields placeholders.
It would be really hard (if possible) to achieve what you are trying to do by injecting spaces into the text because each character in the font has a different width unless you use a monospaced font.
https://en.wikipedia.org/wiki/Monospaced_font
Instead, I would recommend a different approach. Override the text field, provide two UILabels and adjust their position using Autolayout.
Below is my code. I'm trying to change the color of the text inside tableViewCell by using if condition that if the string contains - sign then it should go red or else green but it turns out all the strings go green.
cell.percentLabel.text = PercentChange[indexPath.row]
for i in PercentChange{
if (i.range(of: "-") != nil) {
cell.percentLabel.textColor = UIColor.red
} else {
cell.percentLabel.textColor = UIColor.green
}
}
Assuming your posted code is in your cellForRowAt method, you should not be looping through all of the PercentChange values.
As written, you set the color of every cell based on the last value in PercentChange.
You should only be looking at the value specific to the given row.
let change = PercentChange[indexPath.row]
cell.percentLabel.text = change
cell.percentLabel.textColor = change.range(of: "-") != nil ? .red : .green
For a pure matter of training I'm developing a weather app coding the entire UI rather than using storyboard.
I have a nested structure of views as follows:
SuperView --> UIView (with 5 subviews of type UIView).
Each of the 5 UIViews contains: 1 UIImageView, 2 UILabels
Now, when I'm calling my delegate function to retrieve the weather I'm having trouble updating those values with weather icon, weather description, day.
I tried using Tags for each of the subviews but no joy.
To give you something to look at:
This is where I retrieve my forecast data (icons, description, day):
//MARK: Forecast Wheel elements
let forecastWeatherWheel = UIView()
var forecastDays = [String]()
var forecastDescriptions = [String]()
var forecastIcons = [String]()
func setForecastWeather(forecast: ForecastWeatherData) {
forecastDays = forecast.forecastDay
forecastDescriptions = forecast.weatherDescription
forecastIcons = forecast.icon
for (index,forecastContainerView) in (forecastWeatherWheel.subviews.filter{$0 is UIView}).enumerated(){
for (index,iconImageView) in (forecastContainerView.subviews.filter{$0 is UIImageView}).enumerated(){
let iconImage = iconImageView as! UIImageView
iconImage.image = UIImage(imageLiteralResourceName: forecastIcons[index])
}
}
}
With that nested for I've been - somehow - able to access the image property of my nested view but rather than looping through the array of icons it's using always the same Icon in all the 5 subviews...
Any help is highly appreciated as I'm struggling with this since more than 12 hrs :|
The real answer is of course to use a view subclass, with accessors for the image view and each label, instead of using the subview hierarchy like this. But here's what's wrong with what you're doing right now:
for (index,forecastContainerView) in (forecastWeatherWheel.subviews.filter{$0 is UIView}).enumerated(){
The filter here is pointless; everything in subviews is a UIView. You'll get 5 passes through here.
for (index,iconImageView) in (forecastContainerView.subviews.filter{$0 is UIImageView}).enumerated(){
Your filter here is only going to return a single view - the image view, since the others aren't image views. That means this loop is only going to execute once.
let iconImage = iconImageView as! UIImageView
iconImage.image = UIImage(imageLiteralResourceName: forecastIcons[index])
Which means that index here is your inner index, which is always 0.
Either use a different name for each index variable, or write it something like this (untested, typed in browser):
for (index, forecastContainerView) in forecastWeatherWheel.subviews.enumerated() {
let imageView = forecastContainerView.subviews.first(where: { $0 is UIImageView } ) as! UIImageView
imageView.image = UIImage(imageLiteralResourceName: forecastIcons[index]
}
I have a custom cell with two labels and a image. I receive some data from internet in Json. Everything works fine; every cell fills with the correspondent data. I've added a new label that has to be filled just like the other ones. This is the data:
let cell = tableView.dequeueReusableCellWithIdentifier("friendCell") as! friendCell
cell.friendPicture?.image = newImageUser
cell.friendName.text = "#\(theName[indexPath.row])"
if repliesNumber[indexPath.row] == "0"{
cell.repliesNumber.textColor = UIColor.redColor()
}
else{
cell.repliesNumber.textColor = UIColor(patternImage: UIImage(named:"backgroundPattern")!)
}
if AttachedImage[indexPath.row] != ""{
cell.backgroundColor = .orangeColor()
}
For testing I've made to be colored the first two cells. My issue is that the fist two cells get colored, but if I scroll down, every two, three, four cells (depending on the device -device height I guess-, another two cells get colored too.
It's odd/weird because the rest of labels work fine.
Where should I start looking?
If I print the json data I receive everything is okay
Here is a gif:
GIF
Basically my problem is that when I scroll down the data disappear but only from a label, the rest of labels and images doesn't.
It's not very clear from your code which are the cells that are "colored". Is it from the orangeColor() condition ?
Anyway, UITableViewCells in an UITableView are reused, which means you are given them in the exact same state you left them. This is why, if you don't reset your backgroundColor, they still are orange as you scroll.
So basically, whenever you do something in a certain condition in a cell, don't forget to restore its state when the condition is not met. In your case, this gives :
// cellForRowAtIndexPath {
if itemIsMultimedia() {
cell.Multimedia.text = "it's multimedia"
cell.Multimedia.hidden = false
}
else {
cell.Multimedia.text = ""
cell.Multimedia.hidden = true
}
here #aimak
if AttachedImage[indexPath.row] != ""{
cell.Multimedia.text = "It's multimedia"
}
else{
cell.Multimedia.hidden = true
}
I am using UIPageControl in conjunction with UIScrollView to display 5 images. I would like to be able to set the current page indicator dot color to a different color for each page (when it is selected). I have tried setting the currentPageIndicatorTintColor in the Value Changed action of the UIPageControl, but this shows the previous color briefly before changing to the new color.
Does anyone know if its possible to use different colors for each dot, in such a way that the display is seemless?
Note: this is not a duplicate of How can i change the color of pagination dots of UIPageControl? because that question is about changing all the dots to have the same color, whereas I would like to change the individual page dots to have different colors when their page is currently showing.
This is how you can do this:
Step 1: Subclass UIPageControl and add a property dotImages to hold images for all dots.
class MyPageControl : UIPageControl {
var dotImages : [UIImage?] = []
Step 2: Initialise your dotImages
required init(coder: NSCoder) {
super.init(coder: coder)!
let firstDotImage = UIImage.init(named: "dot1.png")
let secondDotImage = UIImage.init(named: "dot2.png")
let thirdDotImage = UIImage.init(named: "dot3.png")
let fourthDotImage = UIImage.init(named: "dot4.png")
let fifthDotImage = UIImage.init(named: "dot5.png")
dotImages = [firstDotImage, secondDotImage, thirdDotImage, fourthDotImage, fifthDotImage]
}
Step 3: Implement updateDots function to set your own image
func updateDots () {
for var index = 0; index < self.subviews.count; index++ {
let dot = self.subviews[index] as! UIImageView
dot.image = self.dotImages[index]
}
}
Step 4: Call updateDots function based on you app need. You may call it initially while view is loading or may be while page is changing.
currentPageIndicatorTintColor WILL work.
You might have to actually do a bit of work here.
func scrollViewDidScroll(scrollView: UIScrollView) {
//If the page is over 50% scrolled change the dot to the new value.
//If it is less, change it back if the user is holding the page.
}
What I am suggesting is listen to the scrollview, and pre-empt the page, rather than waiting for the fact to happen. My Psuedo-code is kept abstract, but if this is not enough I can modify the answer more specifically depending on your code if you provide examples.
You must therefore be a UIScrollViewDelegate