iOS_Basic
iOS_Basic
Setting up a UIButton
let button = UIButton(type: .system)
button.setTitle("Click Me", for: .normal)
button.frame = CGRect(x: 100, y: 200, width: 200, height: 50)
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
view.addSubview(button)
Adding a UIImageView
let imageView = UIImageView()
imageView.image = UIImage(named: "example.png")
imageView.contentMode = .scaleAspectFit
imageView.frame = CGRect(x: 100, y: 300, width: 200, height: 200)
view.addSubview(imageView)
Variable Declaration
var greeting: String = "Hello, Swift!"
Function Definition
func addNumbers(a: Int, b: Int) -> Int { return a + b }
Using Optionals
var optionalString: String? = "Hello!"
print(optionalString ?? "No value")
Creating a Class
class Dog {
var name: String
init(name: String) {
self.name = name
}
func bark() {
print("Woof! My name is \(name)")
}
}
let dog = Dog(name: "Buddy")
dog.bark()
advertisement
Using Storyboards and Interface Builder Tutorial
Using Storyboards and Interface Builder allows developers to design the user interface of an iOS
application visually. Storyboards provide a way to create and manage the flow of the app through
various view controllers, transitions, and segues. Interface Builder is integrated within Xcode, enabling
drag-and-drop design, automatic layout adjustments, and configuration of UI components without
needing extensive coding.
Copy
Basic UIButton Creation
let button = UIButton(type: .system)
button.setTitle("Press Me", for: .normal)
button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
view.addSubview(button)
func setupUI() {
myLabel.translatesAutoresizingMaskIntoConstraints = false
myButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(myLabel)
view.addSubview(myButton)
func setupStackView() {
stackView.axis = .vertical
stackView.spacing = 10
stackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stackView)
stackView.addArrangedSubview(label)
stackView.addArrangedSubview(button)
}
}
Scaling Animation
UIView.animate(withDuration: 0.5, animations: {
myView.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
}, completion: { _ in
myView.transform = .identity
})
Position Animation
UIView.animate(withDuration: 0.5) {
myView.center = CGPoint(x: 200, y: 200)
}
Rotation Animation
UIView.animate(withDuration: 1.0) {
myView.transform = CGAffineTransform(rotationAngle: .pi)
}
Spring Animation
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5,
initialSpringVelocity: 0.5, options: [], animations: {
myView.center.y += 200
}, completion: nil)