【问题标题】:UIButton Frame Not Resizing with ImageUIButton 框架未随图像调整大小
【发布时间】:2017-01-12 18:02:58
【问题描述】:

我创建了一个 UIButton,使用图像作为按钮。但是,我无法调整图像/按钮的大小。我使用的代码是:

let leftArmImage = UIImage(named: "LeftArm") as UIImage?
let leftArmButton   = UIButton(type: UIButtonType.custom) as UIButton
leftArmButton.frame = CGRect(x:self.view.center.x + 200,y:self.view.center.y,width:500,height:500)
leftArmButton.setImage(leftArmImage, for: .normal)
leftArmButton.imageView?.frame = leftArmButton.frame
leftArmButton.addTarget(self, action: #selector(PhysicalExam.bodyPartSingleTapped(_:)), for:.touchUpInside)
self.view.addSubview(leftArmButton)

如何调整图片大小?

【问题讨论】:

  • 您确定您的按钮尚未调整大小,但图像并未覆盖该区域吗?尝试在您认为没有按钮的区域按下,它会触发动作吗? (假设您已将操作附加到按钮)编辑:您的图像设置为哪种内容模式?
  • 不要使用leftArmButton.setImage(),尝试使用leftArmButton.setBackgroundImage(),这样它就可以覆盖整个按钮框架。
  • @Jerland2 按钮正在调整大小,但图像没有。按钮区域正确触发动作。至于图像的内容模式,我尝试循环浏览所有三个选项,但都没有填满框架。

标签: ios swift uiimageview uibutton


【解决方案1】:

试试这个

以编程方式

button.setImage(image, for: .normal)
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill

故事板

  1. 打开故事板

  2. 选择属性检查器内的按钮(右侧) -> 在“控制”部分 -> 为水平和垂直对齐选择第四个选项(最后一个)。

【讨论】:

    【解决方案2】:

    尝试使用leftArmButton.setBackgroundImage()代替leftArmButton.setImage(),这样它就可以覆盖整个按钮框架。

    【讨论】:

    • 这似乎仍然没有填满按钮框架。我使框架可见,以便我可以验证这一点
    【解决方案3】:

    试试这个

    leftArmButton.imageView?.contentMode = .scaleAspectFill
    

    【讨论】:

    • 它说 UIContentMode 没有成员 'aspectFill'
    • 对不起,我不在电脑前,但我更新了答案。如果它不起作用,只需输入 . 并等待 xcode 弹出选项以将其自动填充为 wi AspectFill。
    • 没问题。这是一个选项,但它没有调整图像大小
    猜你喜欢
    • 2021-07-01
    • 2021-05-10
    • 1970-01-01
    • 2013-08-26
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多