Swift change the position of a button - ios

In the following piece of code I try to move a button and update the score label.
When I move the button the button moves exactly as I intended, but when I update the label as well the button just stays on the same coordinates.
In the piece of code below everything works great.
#IBAction func clickButtonTapped(_ sender: Any) {
if inGame == false {
segmentedControl.isHidden = true
inGame = true
score = 0
} else {
clickButton.isHidden = true
let height = arc4random_uniform(UInt32(screenHeight))
let width = arc4random_uniform(UInt32(screenWidth))
clickButton.center.x = CGFloat(width)
clickButton.center.y = CGFloat(height)
score += 1
clickButton.isHidden = false
}
}
But when I add this below score += 1 the button does not move anymore.
scoreDisplay.text = String(score)
How can I get the button to move and get to scoreDisplay updated?

Related

Overlapping UIImageViews on screen: select the right view

I am creating an iPhone app in which the user taps structures on an image of an MRI scan to select regions of interest and calculate a score. Each screen contains a UIView with multiple UIImage views. Each UIImageView that is touched by the user is "highlighted". However, on one of the screens the structures of interest are so close together that the frame rectangles of the UIImageView overlap (3 of them). Now, tapping in some areas highlights the wrong image. Rearranging views does not help (moving to front or back) doesn't help, there is a large area of overlap. I included a screen shot of the Storyboard and corresponding code of the view controller. Can anybody think of a solution??
override func touchesBegan(_ touches: Set, with event: UIEvent?)
{
let touch = touches.first!
switch touch.view {
case PO_PV_R:
if PO_PV_R.isHighlighted == false
{
PO_PV_R.isHighlighted = true
loesScore.parieto_occipital_R_perivent = 0.5
}
else
{
PO_PV_R.isHighlighted = false
loesScore.parieto_occipital_R_perivent = 0.0
}
case PO_C_R:
if PO_C_R.isHighlighted == false
{
PO_C_R.isHighlighted = true
loesScore.parieto_occipital_R_central = 0.5
}
else
{
PO_C_R.isHighlighted = false
loesScore.parieto_occipital_R_central = 0.0
}
case PO_SC_R:
if PO_SC_R.isHighlighted == false
{
PO_SC_R.isHighlighted = true
loesScore.parieto_occipital_R_subcortical = 0.5
}
else
{
PO_SC_R.isHighlighted = false
loesScore.parieto_occipital_R_subcortical = 0.0
}
default:
print("default")
}
let score = loesData.shared.totalLoesScore()
scoreLabel.text = String(format:"%.1f", score)
}

Display color on different buttons

So I am making a quiz app, and I am using the following code to display to the user if the answer is correct or wrong.
The app looks like this:
Image here
This is the code to display:
#IBAction func checkAnswer(_ sender: UIButton) {
if let question = currentQuestion, let answer = sender.titleLabel?.text {
if (question.validateAnswer(to: answer)) {
score.incrementCorrectAnswers()
currentScore = currentScore + 1
feedbackLabel.textColor = UIColor(red:0.15, green:0.61, blue:0.61, alpha:1.0)
feedbackLabel.text = "Correct!"
scoreLabel.text = "\(currentScore)"
sender.backgroundColor = hexStringToUIColor(hex: "213F4B")
} else {
score.incrementIncorrectAnswers()
feedbackLabel.textColor = UIColor(red:0.82, green:0.40, blue:0.26, alpha:1.0)
feedbackLabel.text = "Wrong, correct answer is: \n\(currentQuestion!.getAnswer())"
sender.shake()
sender.backgroundColor = hexStringToUIColor(hex: "3F2F4B")
}
answer1Button.isEnabled = false
answer2Button.isEnabled = false
answer3Button.isEnabled = false
answer4Button.isEnabled = false
nextQuestionButton.isEnabled = true
feedbackLabel.isHidden = false
}
}
When using this, if the user tap the wrong button, the button turns red, and if the user taps the correct button, the button turns green. How can I make it so if the user taps the wrong button, the answer on the correct button turns green at the same time as the wrong one goes red? Let me know if any other code from project is necessarily.
You could loop through all UIButton's and check for sender.titleLabel?.text like this:
for view in self.view.subviews as [UIView] {
if let btn = view as? UIButton {
if btn.titleLabel?.text == currentQuestion!.getAnswer() {
btn.backgroundColor = hexStringToUIColor(hex: "213F4B") // Green Color
}
}
}
I'm not on my computer so won't be able to test it, so try it out and let me know how it works.

Is anyone know why the else code part can't hide my colorPicker?

I'm still new with Swift 4 and i found this on the internet & tried to make this Button to show "something" when the image button is A. But when i clicked the Button again, only its image button changed but the "something" still not hidden. Can someone help ?
I already done with other button that using this animation but the button is showing another button from Library.
But this 1 is different, not showing another button from Library but showing ChromaColorPicker
var sizeOff = UIImage(named: "Brush-Size")
var sizeOn = UIImage(named: "Brush-Size-On")
============================ somewhere else ======================
extension ViewController {
#IBAction func BrushColourClicked(_ sender: UIButton) {
if sender.currentImage == ColourOn {
sender.setImage(ColourOff, for: .normal)
} else {
sender.setImage(ColourOn, for: .normal)
} // Image first set
configureUI()
}
func configureUI() {
let colorPicker = ChromaColorPicker(frame: CGRect(x: 25.0, y: 410.0, width: 140.0, height: 140.0)) // Position & Size of Color Picker
ColourButtonCenter = colorPicker.center
colorPicker.center = BrushColour.center
colorPicker.delegate = self
colorPicker.padding = 5.0
colorPicker.stroke = 3.0
colorPicker.hexLabel.isHidden = true
colorPicker.layout()
view.addSubview(colorPicker)
colorPicker.alpha = 0
if BrushColour.currentImage == ColourOn {
UIView.animate(withDuration: 0.35, animations: {
colorPicker.alpha = 1
colorPicker.center = self.ColourButtonCenter
})
} // Animation show
else {
UIView.animate(withDuration: 0.35, animations: {
colorPicker.alpha = 0
colorPicker.center = self.BrushColour.center
})
} // Animation hide
}
}
i dont know if
colorPicker.alpha = 0
is working or not
Every time you call configureUI you're adding a new colour picker to the view, then animating the alpha on it.
So when you're trying to hide the colorPicker what's actually happening is that you're adding a new colour picker with alpha 0 and animating it to alpha 0 (doing nothing), the previous colorPicker will still be visible so it will look as though nothing as changed.
Create a variable for colorPicker once and add it to the view, then configure that instance in your configureUI function.

Getting UIButton to stay highlighted after tap

I'm trying to replicate the scroll selector at the bottom of the emoji keyboard, where you can select the category by tapping on the appropriate icon and it will also show you in which category you are if you scroll. However, I'm having trouble getting the selected button to appear highlighted for some reason. I can get the scroll to work fine, but when I click on the icon it won't stay highlighted. Is this to do with some property of the touchUpInside trigger and the highlighted property?
My Code
var categoryButtons = [UIButton]()
var categoryDistances = [CGFloat]()
func scrollViewDidScroll(_ scrollView: UIScrollView) {
var curIndex = -1
for d in categoryDistances {
if (scrollView.contentOffset.x + 5 >= d) {
curIndex += 1
}
}
for b in categoryButtons {
b.isHighlighted = false
}
if (curIndex == -1) {
curIndex = 0
}
categoryButtons[curIndex].isHighlighted = true
}
func shortcutSelected(_ sender: UIButton) {
snapSelector.contentOffset.x = categoryDistances[categoryButtons.index(of: sender)!]
for b in categoryButtons {
b.isHighlighted = false
}
sender.isHighlighted = true
}
Got it to work the way I wanted by applying a tint color instead of using the isHighlighted or isSelected properties:
let tintedImg = origImg?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
let shortcut = UIButton()
shortcut.setBackgroundImage(tintedImg, for: .normal)
shortcut.tintColor = UIColor.gray

UIButton not reacting to first press in Swift

I am working on a simple (ok, it should be simple) calculator that estimates risk based on a few inputs (toggle on/off)
Everything is working properly, except that the UIButtons need to be tapped 2 times to toggle initially. After that, the UIButtons work as expected.
Here is the code (contained within viewDidLoad())
#IBOutlet weak var confusionButton: UIButton!
var counter = 0
var confusionToggle = 0
and here is the action
#IBAction func pressConfusion(sender: UIButton) {
if confusionToggle == 0 {
confusionButton.backgroundColor = UIColor.clearColor()
confusionButton.alpha = 1;
confusionToggle++;
counter++;
} else {
confusionButton.backgroundColor = UIColor.grayColor()
confusionButton.alpha = 0.5;
confusionToggle = 0
counter--;
}
}
Any thoughts on this one? My Swift skills are very limited (my first attempt with Swift)
Think your just getting yourself confused. Use print statements to first understand what is happening, then do all your fancy button UI changes.
#IBAction func tapButton(sender: UIButton) {
// user println to help debug
println(confusionToggle)
if confusionToggle == 0 {
sender.backgroundColor = UIColor.grayColor()
sender.alpha = 0.5;
confusionToggle++;
counter++;
}
else {
// RESET
sender.backgroundColor = UIColor.clearColor()
sender.alpha = 1;
confusionToggle = 0
counter--;
}
}
I don't know what you trying to do.
Just let you know that confusionToggle will be 0 at first time. So, when you click on the button your first condition will be called, It will clear the background color and increase the value of confusionToggle to 1 then after it's because of 1 it will not go to the first condition. So, it goes to else part and give the background color to the gray. confusionToggle again goes to 0.
And it will iterate every time like 0 - 1 - 0 - 1 ...
If you want to do gray color to the button when you tap then you have to change your logic.
if confusionToggle == 0 {
confusionButton.backgroundColor = UIColor.grayColor()
confusionButton.alpha = 0.5;
confusionToggle = 1;
counter++;
} else {
confusionButton.backgroundColor = UIColor.clearColor()
confusionButton.alpha = 1;
confusionToggle = 0
counter--;
}
Hope it helps to you.

Resources