UIbutton忘记宽度和高度

Posted

技术标签:

【中文标题】UIbutton忘记宽度和高度【英文标题】:UIbutton forgets width and height 【发布时间】:2019-12-15 01:48:06 【问题描述】:

我使用以下方法将 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 图像而不是我的大脑袋。我该如何解决这个奇怪的问题?

【问题讨论】:

【参考方案1】:

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

【讨论】:

好的,但是在按钮已经设置之后如何设置按钮?就像我得到它,如果这是 html 和 CSS 它有一个 ID。但这只有一个 self.tabBarController?.navigationItem.rightBarButtonItem - 我认为你一旦设置就不能重做它? 所以我听到人们说的是将用户个人资料图像存储在会话中,然后在 viewDidLayoutSubview 中重新创建按钮?对吗?

以上是关于UIbutton忘记宽度和高度的主要内容,如果未能解决你的问题,请参考以下文章

给定文本和字体,如何计算 UIButton 的宽度和高度?

Swift:在 UIButton 类中设置宽度和高度

在滚动视图中具有相同宽度和高度的三个 UIButton 上的自动布局

调整 UIButton 宽度/高度 (iOS) - 如何在不禁用自动布局的情况下解决?

如何使用 AutoLayout 配置视图宽度固定宽度和可变高度

如何修复 UIButton 的图像大小?