Implementing the same function for different objects - swift

Newbie coder and learning Swift. I want the function to be applicable for both UIButtons and couldn't figure out how to make it happen for second one.
private lazy var boostButton: UIButton = {
let button = UIButton(type: .custom)
button.frame = CGRect(x: 10, y: 10, width: 80, height: 80)
button.setImage(UIImage(named: "simsek.png"), for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.contentHorizontalAlignment = .center
button.contentVerticalAlignment = .center
button.layer.cornerRadius = 0.5 * button.bounds.size.width
button.layer.masksToBounds = true
button.addTarget(self, action: #selector(touchDown), for: [.touchDown, .touchDragEnter])
button.addTarget(self, action: #selector(touchUp), for: [.touchUpInside, .touchDragExit, .touchCancel])
return button
}()
private lazy var informationButton: UIButton = {
let button = UIButton(type: .custom)
button.frame = CGRect(x: 120, y: 10, width: 35, height: 35)
button.setImage(UIImage(named: "yenigozlukgri.png"), for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.contentHorizontalAlignment = .center
button.contentVerticalAlignment = .center
button.layer.cornerRadius = 0.5 * button.bounds.size.width
button.layer.masksToBounds = true
button.addTarget(self, action: #selector(touchDown), for: [.touchDown, .touchDragEnter])
button.addTarget(self, action: #selector(touchUp), for: [.touchUpInside, .touchDragExit, .touchCancel])
return button
}()
These are my buttons. I don't use storyboard but I believe that's not essential for the solution.
#objc func touchDown() {
animator.stopAnimation(true)
boostButton.backgroundColor = .red
//highlightedColor
}
#objc func touchUp() {
animator = UIViewPropertyAnimator(duration: 0.5, curve: .easeOut, animations: {
self.boostButton.backgroundColor = .gray
})
animator.startAnimation()
}
What I want to do is, when one of the buttons are clicked, it should perform the animation. If I add informationButton like the boostButton to my functions, both of them perform the animation even though one button is clicked. It should work for just the clicked one. How can I fix it to be functional for even more buttons ?

Use the parameter
#objc func touchDown(_ sender:UIButton) {
animator.stopAnimation(true)
sender.backgroundColor = .red
//highlightedColor
}
#objc func touchUp(_ sender:UIButton) {
animator = UIViewPropertyAnimator(duration: 0.5, curve: .easeOut, animations: {
sender.backgroundColor = .gray
})
animator.startAnimation()
}

Related

One UI element for all VC [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How I can create Custom view element with animation like a separate class for all view controllers, so that not write this element each time for each VC.
For example:
I am want create bottom view with button and if I am press on button animation will be appeared, and I am can do different action for different VC.
How I can create this view with animation one time for all VC and implement different action inside VC?
I can only create it each time for each VC, all work done but it's terrible code and sometimes may be hard for maintenance.
This it example how I am create my bottom menu and this way looking good but how work.
import Foundation
import UIKit
class BottomMenu: UIViewController {
static let shared = BottomMenu()
var yPosBottomUIView: CGFloat = 90.0
var yPosCenterButton: CGFloat = 35
var yPosBackButton: CGFloat = 35
var yPosForwardButton: CGFloat = 35
var yPosContextMenu: CGFloat = 35
var yPosUpdateButton: CGFloat = 35
var backButtonEnable: Bool = false
var forwardButtonEnable: Bool = false
lazy var image: UIImageView = {
let image = UIImageView(frame: CGRect(x: 0, y: UIScreen.main.bounds.maxY - yPosBottomUIView, width: UIScreen.main.bounds.width, height: 90))
if (osTheme == .dark) {
DispatchQueue.main.async {
image.image = UIImage(named: "SurfaceBlack")
}
return image
} else {
DispatchQueue.main.async {
image.image = UIImage(named: "SurfaceLight")
}
return image
}
}()
lazy var centerButton: UIButton = {
let button = UIButton(frame: CGRect(x: (UIScreen.main.bounds.maxX / 2) - 25, y: (UIScreen.main.bounds.maxY - 50) - yPosCenterButton, width: 50, height: 50))
if (osTheme == .dark) {
button.backgroundColor = UIColor(red: 0.118, green: 0.118, blue: 0.15, alpha: 1)
} else {
button.backgroundColor = UIColor(red: 0.118, green: 0.118, blue: 0.15, alpha: 1)
}
button.layer.cornerRadius = 25
button.setImage(UIImage(named: "Menu"), for: .normal)
button.addTarget(self, action: #selector(centralButtonAction), for: .touchUpInside)
button.isEnabled = false
return button
}()
lazy var backButton: UIButton = {
let button = UIButton(frame: CGRect(x: (UIScreen.main.bounds.minX) + 25, y: (UIScreen.main.bounds.maxY - 15.5) - yPosBackButton, width: 36, height: 36))
button.backgroundColor = .clear
button.setImage(UIImage(named: "whiteBackArrow"), for: .normal)
button.addTarget(self, action: #selector(centralButtonAction), for: .touchUpInside)
button.isEnabled = backButtonEnable
return button
}()
lazy var forwardButton: UIButton = {
let button = UIButton(frame: CGRect(x: (UIScreen.main.bounds.minX) + 90, y: (UIScreen.main.bounds.maxY - 15.5) - yPosForwardButton, width: 36, height: 36))
button.backgroundColor = .clear
button.setImage(UIImage(named: "whiteBackArrow"), for: .normal)
button.imageView?.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
button.addTarget(self, action: #selector(centralButtonAction), for: .touchUpInside)
button.isEnabled = forwardButtonEnable
return button
}()
lazy var contextMenu: UIButton = {
let button = UIButton(frame: CGRect(x: (UIScreen.main.bounds.maxX) - 60, y: (UIScreen.main.bounds.maxY - 15.5) - yPosContextMenu, width: 36, height: 36))
button.backgroundColor = .clear
button.setImage(UIImage(named: "ContextMenu"), for: .normal)
button.addTarget(self, action: #selector(contextMenuButtonAction), for: .touchUpInside)
return button
}()
lazy var updateButton: UIButton = {
let button = UIButton(frame: CGRect(x: (UIScreen.main.bounds.maxX) - 125, y: (UIScreen.main.bounds.maxY - 15.5) - yPosUpdateButton, width: 36, height: 36))
button.backgroundColor = .clear
button.setImage(UIImage(named: "updateN"), for: .normal)
button.addTarget(self, action: #selector(centralButtonAction), for: .touchUpInside)
button.isEnabled = false
return button
}()
lazy var blur: UIVisualEffectView = {
let blurEffectView = UIVisualEffectView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
let blurEffect = UIBlurEffect(style: .dark)
blurEffectView.effect = blurEffect
blurEffectView.alpha = 0
return blurEffectView
}()
#objc func centralButtonAction(_ sender: UIButton?) {
print("Center Tapped")
}
#objc func contextMenuButtonAction(_ sender: UIButton?) {
print("Context Menu Tapped")
// IF I am past blur effect here and some action for diffent VC nothing happens but each time I'll saw printed text above)
}
}
This is image of menu which I am create but I am write code each time for each VC
Menu have ... when I press on it I am show the same animation for all VC and add some others view BUT When I am closed others sub view I am want implement different action depend of VC where menu did be opened.
Did you tried making one controller as base controller that can be inherited by all child controller and the common actions/activites to be part of that controller. Or maybe using a container view for child controller so that you can inherit properties of your base controller to your child controller.It depends on whatever suits your actual requirements

How to add UIImageView to navigation bar in swift?

I have this code that adds a rounded border around a UIImage using UIImageView and I've used UITapGestureRecognizer to let the user tap on the button:
var profilePicture = UIImageView()
func setupUserProfileButton() {
let defaultPicture = UIImage(named: "profilePictureSmall")
profilePicture = UIImageView(image: defaultPicture)
profilePicture.layer.cornerRadius = profilePicture.frame.width / 2
profilePicture.clipsToBounds = true
profilePicture.layer.borderColor = UIColor.black.cgColor
profilePicture.layer.borderWidth = 1
// Letting users click on the image
profilePicture.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(profilePictureTapped))
profilePicture.addGestureRecognizer(tapGesture)
}
How can I add this to the left side of a navigation bar? Is it possible? And I don't think the tap gesture is needed if I can add the ImageView to the navigation bar as a barButtonItem, so you can ignore that. I kinda found some similar questions but they were in objective C and none of what I tried worked.
Here is what I came up with based on an answer:
import UIKit
import Firebase
class CreateStoryPage: BaseAndExtensions {
let userProfileButton = UIButton(type: .custom)
override func viewDidLoad() {
super.viewDidLoad()
// Call all the elements
setupUserProfileButton()
}
// MARK:- Setups
// Setup the user profile button
func setupUserProfileButton() {
userProfileButton.setImage(#imageLiteral(resourceName: "profilePictureSmall.png"), for: .normal)
userProfileButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
userProfileButton.addTarget(self, action: #selector(profilePictureTapped), for: .touchUpInside)
let userProfileView = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
userProfileView.layer.cornerRadius = 14
userProfileView.backgroundColor = .red
userProfileView.addSubview(userProfileButton)
let leftNavBarItem = UIBarButtonItem(customView: userProfileView)
self.navigationItem.setLeftBarButton(leftNavBarItem, animated: true)
}
// if user taps on profile picture
#objc func profilePictureTapped() {
let userProfilePage = UserProfilePage()
present(userProfilePage, animated: true, completion: nil)
}
}
Try this;
private func setupRightItem() {
let userProfileButton = UIButton(type: .custom)
userProfileButton.imageView?.contentMode = .scaleAspectFill
userProfileButton.clipsToBounds = true
userProfileButton.addTarget(self, action: #selector(profilePictureTapped), for: .touchUpInside)
userProfileButton.setImage(#imageLiteral(resourceName: "profilePictureSmall.png"), for: .normal)
userProfileButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: userProfileButton)
userProfileButton.widthAnchor.constraint(equalToConstant: 30).isActive = true
userProfileButton.heightAnchor.constraint(equalToConstant: 30).isActive = true
}
#objc private func goProfile() {
/// -> Action
}
let navBtn = UIButton(type: .custom)
navBtn.setImage("yourImage", for: .normal)
navBtn.frame = CGRect(x: 0, y: 0, width: 28, height: 28)
navBtn.addTarget(self, action: #selector(self.openProfile(_:)), for: .touchUpInside)
let view = UIView(frame: CGRect(x: 0, y: 0, width: 28, height: 28))
view.cornerRadius = 14
view.backgroundColor = Global.colorBlue
view.addSubview(navBtn)
let leftNavBarItem = UIBarButtonItem(customView: view)
self.navigationItem.setLeftBarButton(leftNavBarItem, animated: true)
#objc
func openProfile(_ sender: UIButton) {
}

How to have a button call a method programmatically in a class in swift?

I want the button to slide off the screen when it's hit, but that part of the code (buttonPressed) isn't working. When the method buttonPressed is inside the class, nothing happens when the button is pressed. Move the method outside of the brackets (to right before viewDidLoad) and the code executes. However, then it slides the entire view as opposed to just the tutorial window. I either need to find a way to make buttonPressed work as a method of the Tutorial class, or find a way to make it refer to the specific instance of "view" that's called in the class.
I'm new to coding and very new to methods, so any help is appreciated!
class Tutorial{
var label = UILabel()
var view = UIView()
var button = UIButton()
init (text: String){
view = UIView()
label = UILabel(frame: CGRect(x: 10, y: 10, width: 180, height: 90))
button = UIButton(frame: CGRect(x: 50, y: 110, width: 100, height: 30))
view.backgroundColor = .white
view.layer.cornerRadius = 15
view.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .center
label.text = text
label.numberOfLines = 10
label.backgroundColor = .white
label.textColor = UIColor(red:0.12, green:0.15, blue:0.23, alpha:1.0)
button.backgroundColor = UIColor(red:0.23, green:0.72, blue:0.44, alpha:1.0)
button.setTitleColor(.white, for: .normal)
button.setTitle("Got it!", for: .normal)
button.layer.cornerRadius = 15
view.addSubview(label)
view.addSubview(button)
button.addTarget(self, action: #selector(buttonPressed), for: UIControlEvents.touchUpInside)
}
func setConstraints(height: CGFloat){
view.centerXAnchor.constraint(equalTo: view.superview!.centerXAnchor).isActive = true
view.topAnchor.constraint(equalTo: view.superview!.topAnchor, constant: UIScreen.main.bounds.height-300).isActive = true
view.widthAnchor.constraint(equalToConstant: 200).isActive = true
view.heightAnchor.constraint(equalToConstant: height).isActive = true
UIView.animate(withDuration: 0.5, delay: 0.2, options: [], animations: {
self.view.center.x -= UIScreen.main.bounds.width
})
}
#objc func buttonPressed(){
print("Pressed")
UIView.animate(withDuration: 0.5, delay: 0.0, options: [], animations: {
self.view.center.x -= UIScreen.main.bounds.width
},
completion: { (finished: Bool) in
self.view.isHidden = true
})
}
}
override func viewDidLoad() {
super.viewDidLoad()
let tutorial1 = Tutorial(text: "Click and hold to see the anatomy overlay")
self.view.addSubview(tutorial1.view)
tutorial1.setConstraints(height: 150)
Try using Interface Builder Constants. Here is the Apple Documentation. https://developer.apple.com/documentation/appkit/constants/interface_builder_constants?language=objc
make an IBOutlet and an IBAction for your button.

Swift 3: How can I add the buttons on the UIWeb View

I am doing a project and I want to add 6 buttons on the webview , but whenever I am trying to add a button, the app doesnot show this button.
Any suggestion, help really appreciated!
Thanks
Try This-
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
button.backgroundColor = UIColor.redColor()
button.addTarget(self, action: #selector(ratingButtonTapped), forControlEvents: .TouchUpInside)
self.profileVIew.addSubview(button)
func ratingButtonTapped(){
print("Button pressed")
}
I'm going to show you how to do this in code without using storyboards. Put his in your view controller class
var setupButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = UIColor(r: 80, g: 101, b: 161, a: 256)
button.setTitle("Register", for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
button.addTarget(self, action: #selector(handleRegister), for: .touchUpInside)
return button
}()
then in your viewDidLoad() function put
view.addSubview(setupButton)
myButton()
then outside of viewDidLoad() put
func myButton() {
setupButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
setupButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
setupButton.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -24).isActive = true
setupButton.heightAnchor.constraint(equalToConstant: 150).isActive = true }
func handleRegister {
#your action here
}

swift - UIBarButtonItem UIButton view alpha not working

I'm creating a uibutton in an extension with the following code:
extension UIButton {
func customButton(_ title: String, selector: Selector) -> UIButton{
let button = UIButton()
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.black.cgColor
button.titleLabel!.font = UIFont.systemFont(ofSize: 16)
button.setTitle(title, for: UIControlState())
button.setTitleColor(UIColor.black, for: UIControlState())
button.setTitleColor(UIColor(r: 220, g: 220, b:220), for: .highlighted)
button.titleEdgeInsets = UIEdgeInsetsMake(8, 8, 8, 8)
button.layer.cornerRadius = 5
button.sizeToFit()
button.addTarget(self, action: selector, for: .touchUpInside)
button.frame = CGRect(x: 0, y: 0, width: 80, height: 30)
button.alpha = 0.4
return button
}
}
The problem is that I'm using this button as a custom view in a UIBarButtonItem:
UIBarButtonItem(customView: self.customButton!)
That button is settingt he alpha to 0.4 but the button still shows up with full alpha!
I even tried switching it in the class after calling the customButton method and it simply does not work.
I'm trying to make the button seem disabled on first open and it's impossible to get that alpha to work.
Not sure why this is happening but I added this and we're good now.
override func viewWillAppear(_ animated: Bool) {
button?.alpha = 0.4
}
For some reason putting it in the viewWillAppear makes it so that the alpha is 0.4 on load.