UIButton 从各个方向填充在图像内部

问题描述 投票:0回答:2

我有一个带有 a) 图像和 b) 背景图像的按钮 - 全部内置在故事板中。由于背景图像具有不同的形状,图像从按钮中弹出。我想给实际图像 (a) 一些来自各个方向的填充,以便它可以收缩到背景图像内。我无法使用插图来做到这一点,因为它们只为非相对侧提供填充,当相同的插图设置为相对侧时 - 图像不会缩小。很高兴知道它是如何在故事板和编程中完成的。

ios swift xcode uibutton uiimage
2个回答
29
投票

您应该设置按钮来填充图像。这样做可以让您使用图像插图作为填充。请注意,这会拉伸图像,因此如果您想要正确的宽高比,则需要在左/右与上/下适当填充。

在故事板中,您可以在按钮控制部分执行此操作。然后调整按钮的图像插图。

在代码中你确实喜欢这样。

button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
button.imageEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)

0
投票

适用于 iOS 15+

// 1. Create configuration for your button
  var configuration = UIButton.Configuration.plain() // there are several options to choose from instead of .plain()
         
// 2. Here is your content Insets               
  configuration.contentInsets = NSDirectionalEdgeInsets(top: 24, leading: 24, bottom: 24, trailing: 24)
        
// 3. This is my Button and you can set to your Button the configuration
  myButton.configuration = configuration
    
// 4. Hehe this step is just for fun, Swift is fun <3

ps.

旧版 iOS 版本不会退出,仅适用于 15+

© www.soinside.com 2019 - 2024. All rights reserved.