【问题标题】:How to add constraints for the UIButton and make it move after an action programmaticaly?如何为 UIButton 添加约束并使其在操作后以编程方式移动?
【发布时间】:2019-03-27 03:18:51
【问题描述】:

我在我的项目中使用了一些 cocapods(DKCircleButton = UIButton made in 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")
}

【问题讨论】:

    标签: swift uibutton xcode10.1


    【解决方案1】:

    主要问题实际上是一个非常常见的问题:您尝试访问定义范围之外的变量。您的let button 在viewDidLoad() 内部定义,因此只能从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")
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-28
      相关资源
      最近更新 更多