0

I'm using some cocapods (DKCircleButton = UIButton made in OBJ-c) in my project and I'm trying to add constraints and make my button move to the bottom after the user taps. I've tried every possible solution but none of them worked.

Here's the code I have.

override func viewDidLoad() {
    super.viewDidLoad()

    let button = DKCircleButton(frame: CGRect(x: 0, y: 0, width: 150, height: 150))
    button.center = CGPoint(x: 160, y: 200)
    button.setTitle("Отмазаться", for: .normal)
    button.titleLabel?.font = UIFont.systemFont(ofSize: 20)
    button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
    button.animateTap = true
    button.backgroundColor = UIColor(red: 230/255, green: 103/255, blue: 103/255, alpha: 1.0)
    self.view.addSubview(button)

    let xPosition:CGFloat = 110
    let yPosition:CGFloat = 200
    let buttonWidth:CGFloat = 150
    let buttonHeight:CGFloat = 150

    button.frame = CGRect(x:xPosition, y:yPosition, width:buttonWidth, height:buttonHeight)

}

@objc func buttonPressed(sender: DKCircleButton) {
    // here's should be action associated with a tap, but it doesn't work at all
    // for example, I've tried to change the title of the bottom but this function doesn't recognise the "bottom" identifier
    print("got it")
}

1 Answers1

1

The main problem is actually a very common one: you try to access a variable outside of the scope where it is defined. Your let button is defined inside viewDidLoad() and thus only accessible from within viewDidLoad(). To be able to change stuff in another function, you could make a more global reference and then load it in viewDidLoad(), like so:

var button : DKCircleButton!

override func viewDidLoad() {
    super.viewDidLoad()

    button = DKCircleButton(frame: CGRect(x: 0, y: 0, width: 150, height: 150))
    button.center = CGPoint(x: 160, y: 200)
    button.setTitle("Отмазаться", for: .normal)
    ....//no more changes here

}

@objc func buttonPressed(sender: DKCircleButton) {
    var newFrame = button.frame
    newFrame.width = 200 // You can change whatever property you want of course, this is just to give an example.
    button.frame = newFrame

    print("got it")
}

Make sure the button variable is within the same class, but outside of any other function.

Eric
  • 1,210
  • 8
  • 25