copying label text to clipboard when clicked [duplicate] - swift

This question already has answers here:
How to make a UILabel clickable?
(12 answers)
Closed 3 years ago.
first I have to make UILabel clickable and when it clicked it should copy its text to clipboard. I am using Xcode 10 with swift 5.1.
so firstly I am expecting label to be clickable and after that, this click action copy its text to clipboard. this is a basic level program.

To make the label "clickable" :
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(labelDidGetTapped:))
yourLabel.userInteractionEnabled = true
yourLabel.addGestureRecognizer(tapGesture)
Then, to retrieve the text from the label and copy it to the clipboard :
#objc
func labelDidGetTapped(sender: UITapGestureRecognizer) {
guard let label = sender.view as? UILabel else {
return
}
UIPasteboard.general.string = label.text
}
Note that there won't be any effect when tapping the text, it would be best to present some kind of feedback to the user, by animating the label's alpha for example

Part one of the answer can be followed as -
#IBOutlet weak var clickAble: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// this code is for making label clickable.
clickAble.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer.init(target: self, action: #selector(tapFunction))
tap.numberOfTapsRequired = 1
clickAble.addGestureRecognizer(tap)
}
Part 2nd of answer is as-
#objc func tapFunction(sender:UITapGestureRecognizer)
{
// this is for copying label text to clipboard.
let labeltext = clickAble.text
UIPasteboard.general.string = labeltext
}
}

Try making user interaction enabled. For example:
yourLabel.isUserInteractionEnabled = true
Check this previous thread. This question has already been answered.
How to make a UILabel clickable?

For copying text to your clipBoard.
UIPasteboard.general.string = yourLabel.text

Related

How to create an effect to highlight correct answer

I am learning Swift, and I am throwing myself in the deep end to force myself to learn the language. I have a nephew who is a baby and thought to make an app to help him learn numbers.
The app is designed to set a set number of buttons on the screen like the one provided below. I have the code to play Directions, which tells the user which number to select. A-N14a, the audio file, says to click the 4. The Done button is set to move to the next screen.
What I am asking is that if I want 4 to be pressed, and they press the 9, I want to know how to implement a feature to give a hint to click the number 4? The idea is to change the background to a button, but I don't know how to implement the feature. I am also open to other ideas. As a note, I do not know what to do, and I'm trying to learn, so the code provided is probably very simplistic and is at the beginning stages.
Below is an image of the screen and the code for that page.
ScreenShot of Page
import UIKit
import AVFoundation
class Intervention_Numerals1: UIViewController {
#IBOutlet weak var Directions: UIButton!
#IBOutlet weak var Done: UIButton!
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
setUpElements()
//Audio Test
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "A-N14a", ofType:"mp3")!))
audioPlayer.prepareToPlay()
} catch {
print(error)
}
}
func setUpElements() {
// Style the elements
Utilities.styleFilledButton(Directions)
Utilities.styleFilledButton(Done)
}
#IBAction func Play(_ sender: Any) {
audioPlayer.play()
}
}
Please let me know any tips or advice or links to similar questions, even though I could not find any on my own.
Here's what I would do:
Record the sound "Tap the number" and then the sounds for the numbers 0 through 9. Name the number sounds "0.mp3" through "9.mp3"
Create a storyboard with 4 buttons on it (like the picture you posted.)
Set up button IBOutlets buttonA - buttonD. Put those buttons into an array:
let buttonsArray = [buttonA, buttonB, buttonC, buttonD]
Fill an array with the numbers 0-9. Shuffle it. Remove 4 values put them into an array "buttonValues" (use the method removeLast().) The code to generate non-repeating values from 0-9 might look like this:
var randomNumbers = [Int]() //Define an array to hold random Ints
var lastValueReturned: Int?
//Function to return a random Int. It won't return the same value twice
func randomNumber() -> Int {
//Remove and return an item from the array
var result: Int
repeat {
//If the array is empty, fill it with the shuffled numbers 0...9
if randomNumbers.isEmpty {
randomNumbers += Array(0...9).shuffled()
}
result = randomNumbers.removeLast()
} while result == lastValueReturned
lastValueReturned = result
return result
}
Loop through your array of buttonValues and install the string for each number as the title of one of your buttons:
for index = 0...3 {
buttonsArray[index].setTitle("(buttonValues[index])", forSate: .normal)
}
Pick an index 0-3 to be the "correct" number.
let indexToPick = Int.random(in: 0...3)
Look up that value in buttonValues, and use it to pick a sound file to play:
let numberToPick = buttonValues[indexToPick]
let soundName = "\(numberToPick).mp3"
Load and play the "tap the number" sound, and then Load and play the sound for the selected number (soundName).
When the user taps a button, have the IBAction method use the sender parameter that is passed to it, and look in the array of buttons, buttonsArray, to see which button index was tapped.
If it is the correct button, take the success action.
If the tapped button index is not indexToPick, do an animation that changes the background color of the button at indexToPick, or the button's border width, or something, and then animates it back to normal. (Look at the UIView animate(duration:) family of methods for how to animate the button's background color. Use the form that takes an options: parameter, and set the .autoreverse option.)
If you're a newbie to iOS development, figuring out how to animate your correct answer button could be a challenge. I created a sample project that just animates one of 4 random buttons: https://github.com/DuncanMC/ButtonAnimation.git
The code for that project is as follows:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var buttonA: UIButton!
#IBOutlet weak var buttonB: UIButton!
#IBOutlet weak var buttonC: UIButton!
#IBOutlet weak var buttonD: UIButton!
//Define an empty array to hold buttons.
var buttonsArray = [UIButton]()
override func viewDidLoad() {
super.viewDidLoad()
//Put our button outlets into an array so we can reference them by index.
buttonsArray = [buttonA, buttonB, buttonC, buttonD]
//Give our buttons a cornerRadius so they look rounded when we add a border and fill color
for button in buttonsArray {
button.layer.cornerRadius = 10
}
}
#IBAction func handleAnimateButton(_ sender: UIButton) {
sender.isEnabled = false
//Pick a random button
let button = buttonsArray.randomElement()!
//Create an auto-reversing animation that fills the button with cyan, and draws a border around it.
//(Showing the border won't fade in and out, but it doesn't really matter)
UIView.animate(withDuration: 0.25,
delay: 0,
options: [.autoreverse, .curveEaseInOut],
animations: {
button.backgroundColor = .cyan
button.layer.borderWidth = 1.0
}, completion: {
success in
button.backgroundColor = .clear
sender.isEnabled = true
button.layer.borderWidth = 0
})
}
}
I would do as follows:
1. Create as many IBOutlets as your numbers (I suppose 0-9 for your example?) and link them to your buttons - E.g.
#IBOutlet weak var Button1: UIButton!
#IBOutlet weak var Button2: UIButton!
// Create as many as you need - Probably 10?
2. Create an IBAction and link it to all your buttons, with this code
#IBAction func checkCorrectAnswer(_ sender: UIButton) {
let arrayOfButtons:[UIButton] = [Button1, Button2] // Here you add all your buttons
let buttonTitle = sender.title(for: .normal)!
if buttonTitle == "YOUR CORRECT ANSWER" { //You have to substitute "YOUR CORRECT ANSWER" with the right string value
sender.backgroundColor = .green
} else {
sender.backgroundColor = .red
for i in arrayOfButtons {
if i.titleLabel?.text == "YOUR CORRECT ANSWER" { i.backgroundColor = .orange }
}
}
}
Enjoy!

I can't change the text of a UILabel in Swift

I am trying to change the text of a UILabel in my code, but the text won't change.
I tried to use the well-known command for changing the text, "NameOfLabel.text = 'Hello", but that did not work. So I tried to put it in a start function so you would click a UIButton and it would change the text, didn't work either.
#IBOutlet var nameOfRobot: UILabel!
#IBAction func startButton(_ sender: Any){
let nameNumber = Int.random(in: 1...3)
if nameNumber == 1 {
self.nameOfRobot.text = "Ben"
}
if nameNumber == 2 {
self.nameOfRobot.text = "Oliver"
}
if nameNumber == 3 {
self.nameOfRobot.text = "Colton"
}
}
I want it to choose a number between 1 and three and have it change the UILabel to that name. When I start the app though, it works, but it doesn't change the text of the label.
Looks like you forgot to connect the action to the button press:
You can tell this is done correctly by looking at the full circle indicator in the editor:
EDIT: Setting the correct class to the viewController in the storyboard:

UILabel Not Updating to match UILabel.text

When I change the text attribute of my UILabel, it only partially updates in the app.
I've tried putting it in the viewDidLoad function and in a separate dedicated function to no avail. If I print the Label.text to the console after the update it is correct, but it doesn't show up properly on screen.
The class in question:
#IBOutlet weak var PromptLabel: UILabel!
var labelText = "";
override func viewDidLoad() {
super.viewDidLoad()
print("view loaded")
self.PromptLabel.text = "Tell Us... " + labelText;
// Do any additional setup after loading the view.
}
Called by:
#IBAction func UsingButtonPressed(_ sender: Any) {
(sender as AnyObject).setTitleColor(UIColor.red, for: .normal)
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil);
let secondController = storyBoard.instantiateViewController(withIdentifier: "Secondary View Controller") as! SecondaryViewController;
secondController.labelText = "What You're Using Today"
self.present(secondController, animated: true, completion: nil)
}
The label should display as "Tell Us... What You're Using Today" but it only shows "Tell U..." which makes no sense.
You need to make sure that the constraint for the UILabel's width is wide enough to accommodate the text. Otherwise, it is being cutoff and the ... you are seeing is because the label's line break is set to truncating tail, which means that the end of the string will be replaced with ... when the label is too narrow.
So this is an interface builder issue and not a Swift-specific issue. The label's text is being correctly updated, the UI is just not able to properly display it.
If you want the width constraint of the label to change dependent on the text, there are ways to calculate the width of the text and update the constraint's constant to accommodate that text's width.

How can I get the contents of the text box below and display the retrieved text on the label when I press the button?

enter image description here
Please tell me what kind of code to write
I suppose you've already created the reference for the textbox as TextView. Now you need to create a new IBOutlet for the label. Once you have the reference to the label you can get the text value from the textview and show it in the label.
#IBAction func display(_sender) {
self.labelView.text = self.TextView.text
//if you want to clear the textview
self.TextView.text = ""
}
Create outlet for your label
#IBOutlet weak var yourlabel: UILabel!
On Button Action right code to set the value to label.
#IBAction func display(_sender) {
yourlabel.text = self.TextView.text
}

How to make a number pad appear without a text box

Hello I am trying to have a number pad appear after a timer is up. Then have my user type numbers on the pad and their input be saved to a variable in my code not a text box. I can't seem to find anything on popping up a number pad without using a text box. Any help is appreciated.
Ok I'm going to give you some code that will greatly help you. You need some sort of UITextView or UITextField to get the system keyboard. So essentially what we will do is have a textField without showing it, and then grab the info off it and store it into the variable.
//Dummy textField instance as a VC property.
let textField = UITextField()
//Add some setup to viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self //Don't forget to make vc conform to UITextFieldDelegateProtocol
textField.keyboardType = .phonePad
//http://stackoverflow.com/a/40640855/5153744 for setting up toolbar
let keyboardToolbar = UIToolbar()
keyboardToolbar.sizeToFit()
let flexBarButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneBarButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissKeyboard))
keyboardToolbar.items = [flexBarButton, doneBarButton]
textField.inputAccessoryView = keyboardToolbar
//You can't get the textField to become the first responder without adding it as a subview
//But don't worry because its frame is 0 so it won't show.
self.view.addSubview(textField)
}
//When done button is pressed this will get called and initate `textFieldDidEndEditing:`
func dismissKeyboard() {
view.endEditing(true)
}
//This is the whatever function you call when your timer is fired. Important thing is just line of code inside that our dummy code becomes first responder
func timerUp() {
textField.becomeFirstResponder()
}
//This is called when done is pressed and now you can grab value out of the textField and store it in any variable you want.
func textFieldDidEndEditing(_ textField: UITextField) {
textField.resignFirstResponder()
let intValue = Int(textField.text ?? "0") ?? 0
print(intValue)
}
I am using storyboard and this is what I did:
drag-drop a text field
On the storyboard, in the attributes inspector (having selected the text field), under "Drawing", select hidden
make an outlet for the text field in your view controller
make sure your view controller extends the UITextViewDelegate
make your current view controller the delegate
in the required location simply call <textfieldOutlet>.becomeFirstResponder()
Now that this is simply a textfield's data, u can always store the value and use it else where.