Copy button from Label.
I have code for the calculator but I can not figure out how to do it so that when I click on the button, the number with the Label is copied. Or how can I make it so that when I press long it appears to copy:
"
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var displayResultLabel: UILabel!
var stillTyping = false
var dotIsPlaced = false
var firstOperand: Double = 0
var secondOperand: Double = 0
var operationSign: String = ""
var currentInput: Double {
get {
return Double (displayResultLabel.text!)!
}
set {
let value = "\(newValue)"
let ValueArray = (value.components(separatedBy:"."))
if ValueArray[1] == "0" {
displayResultLabel.text = "\(ValueArray[0])"
} else {
displayResultLabel.text = "\(newValue)"
}
stillTyping = false
}
}
@IBAction func numberPressed(_ sender: UIButton) {
let number = sender.currentTitle!
if stillTyping {
if (displayResultLabel.text?.characters.count)! < 20 {
displayResultLabel.text = displayResultLabel.text! + number
}
} else {
displayResultLabel.text = number
stillTyping = true
}
}
@IBAction func twoOperandsSignPressed(sender: UIButton) {
operationSign = sender.currentTitle!
firstOperand = currentInput
stillTyping = false
dotIsPlaced = false
}
func operateWithTwoOperands(operation: (Double, Double) -> Double) {
currentInput = operation(firstOperand, secondOperand)
stillTyping = false
}
@IBAction func equalitySignPressed(sender: UIButton) {
if stillTyping {
secondOperand = currentInput
}
dotIsPlaced = false
switch operationSign {
case "+":
operateWithTwoOperands{$0 + $1}
case "-":
operateWithTwoOperands{$0 - $1}
case "×":
operateWithTwoOperands{$0 * $1}
case "÷":
operateWithTwoOperands{$0 / $1}
default: break
}
}
@IBAction func dotButtonPressed(_ sender: UIButton) {
if stillTyping && !dotIsPlaced {
displayResultLabel.text = displayResultLabel.text! + "."
dotIsPlaced = true
} else if !stillTyping && !dotIsPlaced {
displayResultLabel.text = "0."
}
}
}
I will answer both of your questions.
The first question: How to press a button that can copy the text that is being displayed on the
UILabel
?Answer:
The second question: How to long-press on the
UILabel
that shows the "Copy" action?Answer:
To make
UILabel
copyable we need to create a custom class that is a subclass ofUILabel
. Temporarily calledCopyableLabel
:And use a
CopyableLabel
instead of a pureUILabel
:If you use the Interface Builder, make sure you've defined the base class of your Label:
You can implement copy and paste with
UIPasteboard
. You can read and write values over it's propertystring
, e.g.:pastes the current value from the pasteboard into your label, and
copies the value from label to the pasteboard.