skip to Main Content

So I’m following a tutorial, and we have to place buttons into our storyboard.

They have given us a bit of code (which I’m assuming customizes the button) which is the following:

Button(action: {
  print("Button pressed")
}, label: {
    Text("AC").frame(width: 80, height: 80, alignment: .center)
      .background(Color.blue)
    .foregroundColor(.white)
    .cornerRadius(40)
    .font(.title)
})

I’m not sure where to put this, in the view controller? When I do I get an error. Also, how would I connect this code to the button in the story board?

Thanks for the help!
ajn

3

Answers


  1. You can set up the Button outlet like this

        var acButton: UIButton {
        let acButton = UIButton()
        acButton.titleLabel?.text = "AC"
        acButton.backgroundColor = .blue
        acButton.tintColor = .white
        acButton.layer.cornerRadius = 40
        acButton.titleLabel?.font = .yourFont
        acButton.frame = CGRect(x: contentView.center.x,
                                y: contentView.center.y,
                                width: 80,
                                height: 80)
        return acButton
    }
    

    and then create function which will be called when you tap on it

        @objc func acButtonTapped(sender: UIButton!) {
        print("Button Pressed")
    }
    

    and in viewDidLoad

        override func viewDidLoad() {
        super.viewDidLoad()
        acButton.addTarget(self, action: #selector(acButtonTapped(sender:)), for: .touchUpInside)
    }
    
    Login or Signup to reply.
  2. Create an IBOutlet for the button:

    @IBOutlet weak var yourButton: UIButton() 
    

    By assigning the button as an outlet, the button can later be used in storyboard. Now in ViewDidLoad():

    override func viewDidLoad(){
        super.viewDidLoad()
    
        yourButton.setTitle("button", for: .normal)
        yourButton.frame.size = CGSize(width: 80, height: 80)
        yourButton.textLabel?.textAlignment = .center
        yourButton.backgroundColor = .blue
        yourButton.setTitleColor(.white, for: .normal)
        yourButton.layer.cornerRadius = 40
        yourButton.titleLabel?.font = .yourFont
        yourButton.addTarget(self, action: #selector(yourFunction), for: .touchUpInside)
    
       // I don't know if the code below is necessary when using @IBOutlet, but I added it anyways
       view.addSubview(yourButton)
    }
    
    @objc func yourFunction{
        // Do something
    }
    
    
    Login or Signup to reply.
  3. You cannot use SwiftUI view as a UIKit subview, so place it into another SwiftUI view and then you can host it using UIHostingController to add into traditional viewControllers hierarchy.

    Or You can use UIButton instead.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search