如何使按钮正确缩放图像

时间:2020-08-04 19:09:07

标签: swift xcode autolayout uistoryboard

我有一个网球场的图像,以及球场每个区域的按钮。如何使按钮根据设备缩放,但与网球场正确对齐?

我是这方面的新手,所以我将不胜感激!

1 个答案:

答案 0 :(得分:0)

您可以按照vacawama所述(How to get exactly the same point on different screen sizes? )进行自动布局,也可以实施并覆盖

-(void)layoutSubviews { ... } //with Objective-C

override func layoutSubviews() { ... } //with swift
您的UIView中的

。或者,如果您使用了UIViewControler以下

-(void)viewDidLayoutSubviews { ... } //in Objective-C

override func viewDidLayoutSubviews() { ... } //with swift

当UI需要对其内容进行布局时,也会调用这些方法,并且在缩放视图时也是如此。 当您的UIView迅速分配给Objective-C中的-(instancetype)initWithFrame:(CGRect)rect或迅速分配给super.init(frame:CGRect)时,也会调用它。顺便说一句,使用Storyboard实例化也调用了这些方法,这就是为什么在Interface Builder中声明被删除的UIView或ViewController是什么类的原因之一。

要了解有关layoutSubviews的更多信息,请查看此答案https://stackoverflow.com/a/5330162/1443038.

class MyView: UIView {
    // assuming you have declared init() and so on
    // and a var myButton : UIButton 
    override func layoutSubviews() {
        myButton.frame = CGRect(x: 0, y:0, width:self.frame.size.width * 0.2, height:self.frame.size.height * 0.2)
    }
}

class MyViewController : UIViewController {
    // assuming you have declared init() or init(frame:) and so on
    // and a var myButton : UIButton
    override func viewDidLayoutSubviews() {
        //same as example above, but here you ask self.view.frame
        myButton.frame = CGRect(x: 0, y:0, width:self.view.frame.size.width * 0.2, height:self.view.frame.size.height * 0.2)
    }
}