Setting images of a button - ios

I have come across an issue I cannot resolve.
I have a struct and would like to change the image of a button in each collection view. My text/image works as according to plan. However, when trying to change the image button I am struggling. Could someone please help me?
class CollectionViewContent{
var caption = ""
var mainImage: UIImage!
var userProfileImage : UIButton
init(caption: String, mainImage: UIImage!, userProfileImage : UIButton! )
{
self.description = description
self.mainImage = featuredImage
self.userProfileImage = postedUserProfileImage
}
static func showPosts() -> [Posts]
{
return [
Posts(description: "Sweet", mainImage: UIImage(named: "Image 1"), postedUserProfileImage:!),
Posts(description: "Awesome", mainImage: UIImage(named: "Image 2")!),
Posts(description: "WOW!", mainImage: UIImage(named: "Image 3")!
)
]
}
}
This is my collectionViewCell class
class colViewContetCollectionViewCell: UICollectionViewCell {
var posts: Posts! {
didSet {
updateUI()
}
}
#IBOutlet weak var featuredImage: UIImageView!
#IBOutlet weak var postCaptionLabel: UILabel!
#IBOutlet weak var postedUserProfileImage: UIButton!
func updateUI() {
postCaptionLabel?.text! = posts.title
featuredImage?.image! = posts.featuredImage
postedUserProfileImage = posts.postedUserProfileImage
}
override func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = 10.0
self.clipsToBounds = true
}
}
I think this line of code is incorrect by the way, I am not too sure.
postedUserProfileImage = posts.postedUserProfileImage

Instead of:
postedUserProfileImage = posts.postedUserProfileImage
You should do:
postedUserProfileImage.setImage(posts.postedUserProfileImage.image(for: UIControlState.normal), for: UIControlState.normal)
Since postedUserProfileImage is a UIButton, you need to use the setImage method to set it's image for a control specific control state. If no images are set for the other control states, the image for the normal state is used for the others too.
And since posts.postedUserProfileImage is also a UIButton (as mentioned in the comments below) you need to get the button's image via the image(for:) method.

Related

UIImageView Array iOS13

I am trying with learning Swift and got stuck on an issue here.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var diceImageView1: UIImageView!
#IBOutlet weak var diceImageView2: UIImageView!
var leftDiceNumber=1
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
diceImageView1.image = UIImage(imageLiteralResourceName: "DiceSix")
// change transparency with diceImageView1.alpha=0.7
}
#IBAction func rollButtonPressed(_ sender: UIButton) {
print("button pressed")
diceImageView1 = [ UIImageView(imageLiteralResourceName: "DiceOne"),UIImageView(imageLiteralResourceName: "DiceTwo"),UIImageView(imageLiteralResourceName: "DiceThree"),UIImageView(imageLiteralResourceName: "DiceFour"),UIImageView(imageLiteralResourceName: "DiceFive"),UIImageView(imageLiteralResourceName: "DiceSix")],[leftDiceNumber]
leftDiceNumber=leftDiceNumber+1
}
}
But all I get is the error messages on the IBAction:
1.Argument passed to call that takes no arguments
2.Cannot assign value of type '[UIImageView]' to type 'UIImageView'
3.Consecutive statements on a line must be separated by ';'
4.Expected expression
What's the difference between UIImageView and UIImage ? When they should be used?
Many Thanks in advance !
You want to change the .image property to change the image.
To "cycle through" the dice, you could do this:
class DiceViewController: UIViewController {
#IBOutlet weak var diceImageView1: UIImageView!
#IBOutlet weak var diceImageView2: UIImageView!
let diceNames: [String] = [
"DiceOne", "DiceTwo", "DiceThree", "DiceFour", "DiceFive", "DiceSix"
]
var leftDiceNumber = 0
override func viewDidLoad() {
super.viewDidLoad()
diceImageView1.image = UIImage(named: diceNames[leftDiceNumber % 6])
}
#IBAction func rollButtonPressed(_ sender: UIButton) {
print("button pressed")
// increment the index
leftDiceNumber += 1
// udpate the image view
diceImageView1.image = UIImage(named: diceNames[leftDiceNumber % 6])
}
}
I'm guessing your goal is to "randomly roll" the dice, so take a look at this slightly different class:
class DiceViewController: UIViewController {
#IBOutlet weak var diceImageView1: UIImageView!
#IBOutlet weak var diceImageView2: UIImageView!
let diceNames: [String] = [
"DiceOne", "DiceTwo", "DiceThree", "DiceFour", "DiceFive", "DiceSix"
]
override func viewDidLoad() {
super.viewDidLoad()
// start with both dice at One
diceImageView1.image = UIImage(named: diceNames[0])
diceImageView2.image = UIImage(named: diceNames[0])
}
#IBAction func rollButtonPressed(_ sender: UIButton) {
print("button pressed")
// arrays are Zero-based, so get a random Int
// from 0 to 5
//let l = Int.random(in: 0...5)
//let r = Int.random(in: 0...5)
//diceImageView1.image = UIImage(named: diceNames[l])
//diceImageView2.image = UIImage(named: diceNames[r])
// more "modern Swifty" method
if let nm = diceNames.randomElement() {
diceImageView1.image = UIImage(named: nm)
}
if let nm = diceNames.randomElement() {
diceImageView2.image = UIImage(named: nm)
}
}
}

Line spacing doesn't work

I want to change line spacing for my textLabel in storyboard. I select text -> attributed and change paragraph line to 1. If I use textLabel in storyboard everything works fine. But If I connect textLabel in storyboard with my ViewController, this line spacing doesn't work. How to fix it?
My code:
struct Root : Decodable {
let questions : [Question]
}
struct Question : Decodable {
let number, text, rightAnswer : String
}
class ViewController: UIViewController, UITextFieldDelegate {
var questions = [Question]()
#IBOutlet var textLabel: UILabel!
func updateUI(with question: Question) {
title = question.number
textLabel.text = question.text
showAnswerLabel.text = question.rightAnswer
}
}
You can accomplished that by using a lazy var and some property observers. Configure the text styles the way you want in Interface Builder and use this code:
class ViewController: UIViewController {
#IBOutlet weak var textLabel: UILabel!
lazy var defaultAttributes = textLabel.attributedText!.attributes(at: 0, effectiveRange: nil)
var questionText: String {
get { return textLabel.text! }
set { textLabel.attributedText = NSAttributedString(string: newValue, attributes: defaultAttributes) }
}
override func viewDidLoad() {
super.viewDidLoad()
questionText = "What are the color of yellow cab taxi in New York City?"
}
}
Notce that we did not touch textLabel directly to change its text. We do so via the computed property questionText.
Result:

Not woking UIView ishidden after change UILabel text value in swift

I want to change uilabel value and show uiview that has hide like a popup windows.
When I touch a button, that code print "setPopupView 0".
but doesn't show settingView.
and I touch a button again.
print "setPopupView 0" and show settingView.
so When "settingLabelValueUnit text" has changed not show settingView,
but when "settingLabelValueUnit text" has not changed show settingView.
(It means "settingLabelValue text" is same as input value)
I don't know why.
Anyone can help me?
Thank you
here is my swift code.
class ViewController: UIViewController {
#IBOutlet weak var workoutScrollView: UIScrollView!
#IBOutlet weak var settingView: UIView!
#IBOutlet weak var settingLabelValueUnit: UILabel!
#IBOutlet weak var imgSettingBGcal: UIImageView!
#IBOutlet weak var imgSettingBGdis: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.imgSettingBGcal.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(calSettingClick)))
self.imgSettingBGdis.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(disSettingClick)))
}
func calSettingClick(sender: UITapGestureRecognizer) {
setPopupView(0)
}
func disSettingClick(sender: UITapGestureRecognizer) {
setPopupView(1)
}
func showPopup (_ settype:Int) {
switch settype {
case 0:
print("setPopupView 0")
self.settingLabelValueUnit.text = "Set1"
self.workoutScrollView.isHidden = true
self.settingView.isHidden = false
case 1:
print("setPopupView 0")
self.settingLabelValueUnit.text = "Set2"
self.workoutScrollView.isHidden = true
self.settingView.isHidden = false
}
}
}

Generate random image over a button

I'm working on a project to generate random images from an array. I'm running into an issue. I will have one button on the screen name generage shapes. Once the user clicks on this button the generate shapes button becomes hidden and 4 buttons display 4 different shapes. I'm having an issue making these 4 buttons display with the image from my array. I tried a switch statement but it doesn't go through. I'm providing my code below.
import UIKit
class ShapesDetailViewController: UIViewController {
var random = arc4random_uniform(4)
#IBOutlet weak var titleBar: UINavigationItem!
#IBOutlet weak var displayMessageLabel: UILabel!
var myImages = [ "diamond.png", "decagon.png", "dodecagon.png", "hectagon.png", "heptagon.png", "octagon.png", "parallelogram.png", "pentagon.png", "rectangle.png", "rightTriangle.png", "square.png", "trapezoid.png", "triangle.png"]
//my image labels
#IBOutlet weak var buttonOne: UIButton!
#IBOutlet weak var buttonTwo: UIButton!
#IBOutlet weak var buttonThree: UIButton!
#IBOutlet weak var buttonFour: UIButton!
#IBOutlet weak var generateImage: UIButton!
override func viewDidLoad() {
self.buttonFour.hidden = true
self.buttonOne.hidden = true
self.buttonThree.hidden = true
self.buttonTwo.hidden = true
displayMessageLabel.hidden = true
}
#IBAction func generateRandomImages(sender: AnyObject) {
displayMessageLabel.hidden = false
buttonOne.hidden = false
switch(random){
case 0: buttonOne.imageView?.image = UIImage(named: "circle.png")
break
case 1: buttonOne.imageView?.image = UIImage(named: "decagon.png")
break
case 2: buttonOne.imageView!.image = UIImage(named: "diamond.png")
break
case 3: buttonOne.imageView!.image = UIImage(named: "hectagon.png")
break
default:
break;
}
generateImage.hidden = true
}
}
I think the problem is that you can't change a button's image by its image view property, you need to use the setter method for the image. Something like this:
buttonOne.setImage(UIImage(named: "circle"), forState: UIControlState.Normal)

Changes to UIButton Does Not Update Cell Until Scrolled

I solved this using UIButtonState (duhz), but I am curious why exactly this did not work in the first place.
I defined the "normal" icons in the storyboard, then configured it to show the "highlighted" icon when the object is set. However, when the table first loaded, I did not see the updated icon.
But after the table was scrolled, the highlighted icons showed up. What is happening here?
class TweetCell: UITableViewCell {
#IBOutlet weak var profileImage: UIImageView!
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var tweetLabel: UILabel!
#IBOutlet weak var timeStampLabel: UILabel!
#IBOutlet weak var favButton: UIButton!
#IBOutlet weak var replyButton: UIButton!
#IBOutlet weak var retweetButton: UIButton!
var tweet: Tweet!{
didSet {
profileImage.setImageWithURL(NSURL(string:tweet.user.profile_image_url))
nameLabel.text = tweet.user.name
tweetLabel.text = tweet.text
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "h:mm"
let str = dateFormatter.stringFromDate(tweet.createdAt)
timeStampLabel.text = str
if (tweet.favorited) {
favButton.imageView?.image = UIImage(named: "star_highlighted.png")
} else {
}
if (tweet.retweeted) {
retweetButton.imageView?.image = UIImage(named: "retweet_highlighted.png")
} else {
}
}
}
// Before Scrolling
// After Scrolling
This is happening because the tableview is reusing cells which have the highlighted image view. To solve this issue you need to set the unhighlighted image in the else section.
if (tweet.favorited) {
favButton.imageView?.image = UIImage(named: "star_highlighted.png")
} else {
favButton.imageView?.image = UIImage(named: "star_unhighlighted.png")
}
not sure for cause but you can use this to fix,I know you already fix it but still posting the way to fix this issue.
[cell performSelectorOnMainThread:#selector(setNeedsDisplay) withObject:nil waitUntilDone:NO];

Resources