调整大小的背景图像上的UIButton
问题描述:
我想添加一个“日历天”的形象环绕,像这样的一个可点击的UI按钮一些文字:调整大小的背景图像上的UIButton
let button = UIButton()
let X_Offset : CGFloat = (95 * CGFloat(buttonCount)) + 10
let scrollHeight = scrollView.bounds.height
button.frame = CGRect(x: X_Offset, y: scrollHeight/6, width: 70, height: 60)
let buttonText = event.startTime.toShortDayOfWeekString() + "\n" + event.startTime.toShortDayOfMonthString()
button.titleLabel!.lineBreakMode = .byWordWrapping
button.titleLabel!.textAlignment = .center
button.setTitle(buttonText, for: .normal)
button.tag = i
button.backgroundColor = CompanyColor.Red.color
let image = UIImage(named: "calendarDay")
button.setBackgroundImage(image, for: .normal)
button.titleLabel?.font = UIFont(name: "Roboto", size: 14)
button.layer.cornerRadius = 8
button.clipsToBounds = true
答
我想你正在寻找什么是imageEdgeInsets
为UIButton
。设置这些属性可让您移动图像,除了其默认位置。你必须四处游玩才能得到你想要的结果。
有两种方法可以做到这一点。一个使用Interface Builder
,另一个使用编程方式。接口生成器是我猜的最简单的方法。下图显示了如何设置UIButton
的这些属性。
,或者尝试使用编程这样
button.imageEdgeInsets = UIEdgeInsets(top: -10, left: 32, bottom: -10, right: 50)
您可以将标题这样
button.titleEdgeInsets = UIEdgeInsets(top: 0, left:0, bottom: 0, right: 20)
注:设置UIEdgeInsets
这样可能会有不同的结果,如果你有动态大小按钮,例如针对不同的屏幕尺寸。始终确保它看起来像所有屏幕尺寸一样。
嗨Jay,这些似乎对背景图像没有任何影响,只是前景之一。 –
好吧!一种你可以移动背景图像的方法是通过子类“UIButton”,你必须重写'func backgroundRect(forBounds bounds:CGRect)'。我很确定这会适用于你正在寻找的东西。 – Jay