Swift 4.2
仅以编程方式
实现 View
我创建了一个 stack view
并在其中放置了四个按钮,但它们只是没有任何灰色背景的简单按钮。
我想在我的 stackview 中实现精确的四个按钮同样居中,就像 -
button.contentEdgeInset //Not working
这是我试过的-
let feedbackButton:UIButton = {
let origImage = UIImage(named: "feedback")
let tintedImage = origImage?.withRenderingMode(.alwaysTemplate)
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
button.translatesAutoresizingMaskIntoConstraints = false
button.setBackgroundImage(tintedImage, for: UIControl.State.normal)
button.tintColor = .systemPinkColor
button.layer.cornerRadius = 7
button.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 40, bottom: 0, right: 40)
// button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 50)
// button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 50)
button.clipsToBounds = true
button.addTarget(self, action: #selector(feedbackFaculty), for: .touchUpInside)
return button
}()
按钮的图像与插图一起被拉伸(stretch)。 button.imageInsets
和 button.titleInsets
不工作。
帮帮我。谢谢!
最佳答案
背景图像不跟随内容插图。所以这一行:
button.setBackgroundImage(tintedImage, for: UIControl.State.normal)
需要改为:
button.setImage(tintedImage, for: .normal)
此外,这里有几件事需要注意(根据 Apple 的 UIButton
文档):
Supply a title string or image; size the button appropriately for your content.
这意味着您不能同时设置图像和标题,这可能就是您注意到 titleInset
和 imageInset
播放不佳的原因。
但是,如果您只是为按钮设置适当的约束并为标题或图像设置插图,您应该能够获得您想要的外观。还要确保您的堆栈 View 配置为使用等间距分布。
下图中每个按钮的 imageInset
是 (20, 20, 20, 20)
。
关于ios - 如何获得像 iOS map 应用程序模态那样的插入按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52670964/