我在我的项目中使用了一些cocapods(DKCircleButton=UIButton,由OBJ-c制作),我试图添加约束,并在用户点击后将按钮移动到底部。
我试过各种可能的解决办法,但都没有奏效。
这是我的密码。

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")
}

最佳答案

主要问题实际上是一个非常常见的问题:您试图访问定义范围之外的变量。您的let buttonviewDidLoad()中定义,因此只能从viewDidLoad()中访问。为了能够在另一个函数中更改内容,您可以创建一个更全局的引用,然后将其加载到viewDidLoad()中,如下所示:

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")
}

确保button变量在同一个类中,但在任何其他函数之外。

关于swift - 如何为UIButton添加约束并以编程方式使其在执行操作后移动?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55364621/

10-15 14:11