【问题标题】:UIButton's backgroundImage's content mode not respectedUIButton 的 backgroundImage 的内容模式不受尊重
【发布时间】:2016-10-25 17:43:13
【问题描述】:

我正在对即将发布的应用程序进行最后润色,但我发现很难让UIButton 的背景图像中的contentMode 得到尊重。无论我指定的 contentMode 是什么,图像都会在背景中弹出,而与 contentMode 设置无关。

我查看了涵盖此主题的 post,但在我的情况下它似乎没有任何作用。

这是从viewDidLoad调用的:

// I tried putting the contentMode lines here...
myButton.imageView!.contentMode = .scaleAspectFit
myButton.contentMode = .scaleAspectFit
myButton.setBackgroundImage(UIImage(named: "myImage.png"), for: .normal)

// ...and here
// myButton.imageView!.contentMode = .scaleAspectFit
// myButton.contentMode = .scaleAspectFit

// I threw this in for S's & G's to see if it would work...it didn't
myButton.translatesAutoresizingMaskIntoConstraints = false
myButton.imageView?.translatesAutoresizingMaskIntoConstraints = true

我不确定我错过了什么,但我确信这对我来说将是一件非常愚蠢的事情。我欢迎有关如何让UIButton 的背景图像的contentMode 受到尊重的建议。感谢您的阅读。

更新

该按钮被键入为自定义按钮,而不是系统按钮。

【问题讨论】:

    标签: ios swift uibutton


    【解决方案1】:

    问题是您使用setBackgroundImage() 方法添加图像。这会将您的图像添加到一些您无法直接访问的私人UIImageView,例如myButton.imageView!。在您的代码中,您正在为您的按钮应用contentType,而不是其背景图像。

    如果你想达到这个背景UIImageView你需要使用subviews数组。但是如果您尝试在您的viewDidLoad() 方法中执行此操作,您会发现尚未添加背景UIImageView,因为您的按钮layout 方法未被调用。有两种方法可以解决这个问题。

    解决方案 1 – 显式调用 layoutIfNeeded

    override func viewDidLoad() {
        super.viewDidLoad()
    
        myButton.setBackgroundImage(UIImage(named: "myImage"), for: .normal)
        myButton.layoutIfNeeded()
        myButton.subviews.first?.contentMode = .scaleAspectFit
    }
    

    解决方案 2 – 将 contentMode 设置移动到 viewDidAppear 方法。

    override func viewDidLoad() {
        super.viewDidLoad()
    
        myButton.setBackgroundImage(UIImage(named: "myImage"), for: .normal)
        myButton.setTitle("Some title", for: .normal)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    
        myButton.subviews.first?.contentMode = .scaleAspectFit
    }
    

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      为了简化接受的答案,您需要做的就是布局子视图,您的设置代码可以在一个地方完成。

      override func viewDidLoad() {
          super.viewDidLoad()
      
          myButton.setBackgroundImage(UIImage(named: "myImage.png"), for: .normal)
          myButton.layoutIfNeeded()
          myButton.subviews.first?.contentMode = .scaleAspectFill
      }
      

      【讨论】:

        【解决方案3】:

        按钮的 imageView 属性和 backgroundImage 属性是两个不同的东西。

        与接受的答案不同,您可以改用 imageView 属性。

        override func viewDidLoad() {
           super.viewDidLoad()
        
           myButton.setImage(UIImage(named: "myImage.png"), for: .normal)
           myButton.imageView?.contentMode = .scaleAspectFill
        }
        

        【讨论】:

        • 这行得通。谢谢。
        猜你喜欢
        • 2015-01-04
        • 2011-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多