首页 > 解决方案 > UIbutton忘记宽度和高度

问题描述

我使用以下方法将 UIbutton 设置为框架宽度和高度:

let button = UIButton()
button.frame = CGRect(x: 0, y: 0, width: 31, height: 31) //set the frame

那行得通。

在此处输入图像描述

但是,当我关闭应用程序并重新打开时,我会发生这种奇怪的事情,即应用程序无法记住按钮的宽度和高度。

而是这样做(见图),而不是留在 31 乘 31。

右键

现在我如何设置这个按钮?

使用以下代码。

// Image needs to be added to project.
                     let button = UIButton()
                     button.frame = CGRect(x: 0, y: 0, width: 31, height: 31) //set the frame
                     // let modifier = AnyImageModifier { return $0.withRenderingMode(.alwaysOriginal) }
                     button.kf.setImage(with: fburl, for: .normal, placeholder: nil)
                     button.addTarget(self, action: Selector(("yourActionFunc")), for: .touchUpInside)
                     let barButton = UIBarButtonItem()
                     barButton.customView = button
                     self.tabBarController?.navigationItem.rightBarButtonItem = barButton
                    //END FACEBOOK PROFILE IMAGE

我不相信它与上面的代码有任何关系,我认为这与函数有关:

override func viewDidAppear(_ animated: Bool) {

    print(defaults.string(forKey: defaultsKeys.socialLogin))
     self.tabBarController?.navigationItem.title = "DRN1"
    let sessionsocial = self.defaults.string(forKey: defaultsKeys.socialLogin)
    if sessionsocial == nil {
     // Image needs to be added to project.
     let buttonIcon = UIImage(systemName: "person.circle")

    let rightBarButton = UIBarButtonItem(title: "Person", style: UIBarButtonItem.Style.done, target: self, action: #selector(FirstViewController.checkLogin(_:)))
     rightBarButton.image = buttonIcon

      self.tabBarController?.navigationItem.rightBarButtonItem = rightBarButton
       //self.tabBarController?.navigationItem.rightBarButtonItem.backgroundColor = UIColor(patternImage: UIImage(systemName: "ng")
    //self.tabBarController?.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: "person.circle", target: self, action: nil)

    }
  }

但我知道它没有运行该代码,因为我会看到一个 person.circle 图像而不是我的大脑袋。我该如何解决这个奇怪的问题?

在此处输入图像描述

标签: iosswiftuibutton

解决方案


如果您要手动设置按钮的框架,则需要在viewDidLayoutSubviews每次父视图的框架更改时正确设置它。惯用的正确方法是使用自动布局而不是手动调整框架大小。


推荐阅读