我正在尝试创建一个在图标下面有一些文本的按钮(有点像应用程序的按钮),但是这似乎很难实现。你有什么想法吗?我该如何使用UIButton
让文本显示在图片下方呢?
发布于 2012-07-12 10:03:29
在Xcode中,您可以简单地将Edge Title Left Inset设置为图像宽度的负数。这将在图像的中心显示标签。
要让标签显示在图像下方(有点像应用程序按钮),您可能需要将Edge Title Top Inset设置为某个正数。
编辑:下面是一些不使用Interface Builder来实现这一点的代码:
/// This will move the TitleLabel text of a UIButton to below it's Image and Centered.
/// Note: No point in calling this function before autolayout lays things out.
/// - Parameter padding: Some extra padding to be applied
func centerVertically(padding: CGFloat = 18.0) {
// No point in doing anything if we don't have an imageView size
guard let imageFrame = imageView?.frame else { return }
titleLabel?.numberOfLines = 0
titleEdgeInsets.left = -(imageFrame.width + padding)
titleEdgeInsets.top = (imageFrame.height + padding)
}
请注意,如果你使用的是自动布局,并且按钮还没有通过约束在屏幕上进行布局,那么这将不起作用。
发布于 2015-10-03 11:13:38
这是一个简单的居中标题按钮,通过覆盖titleRect(forContentRect:)
和imageRect(forContentRect:)
在Swift中实现。它还实现了与AutoLayout一起使用的intrinsicContentSize
。
import UIKit
class CenteredButton: UIButton
{
override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
let rect = super.titleRect(forContentRect: contentRect)
return CGRect(x: 0, y: contentRect.height - rect.height + 5,
width: contentRect.width, height: rect.height)
}
override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
let rect = super.imageRect(forContentRect: contentRect)
let titleRect = self.titleRect(forContentRect: contentRect)
return CGRect(x: contentRect.width/2.0 - rect.width/2.0,
y: (contentRect.height - titleRect.height)/2.0 - rect.height/2.0,
width: rect.width, height: rect.height)
}
override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
if let image = imageView?.image {
var labelHeight: CGFloat = 0.0
if let size = titleLabel?.sizeThatFits(CGSize(width: self.contentRect(forBounds: self.bounds).width, height: CGFloat.greatestFiniteMagnitude)) {
labelHeight = size.height
}
return CGSize(width: size.width, height: image.size.height + labelHeight + 5)
}
return size
}
override init(frame: CGRect) {
super.init(frame: frame)
centerTitleLabel()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
centerTitleLabel()
}
private func centerTitleLabel() {
self.titleLabel?.textAlignment = .center
}
}
发布于 2016-02-09 03:01:30
看看Swift中的这个great answer。
extension UIButton {
func alignImageAndTitleVertically(padding: CGFloat = 6.0) {
let imageSize = self.imageView!.frame.size
let titleSize = self.titleLabel!.frame.size
let totalHeight = imageSize.height + titleSize.height + padding
self.imageEdgeInsets = UIEdgeInsets(
top: -(totalHeight - imageSize.height),
left: 0,
bottom: 0,
right: -titleSize.width
)
self.titleEdgeInsets = UIEdgeInsets(
top: 0,
left: -imageSize.width,
bottom: -(totalHeight - titleSize.height),
right: 0
)
}
}
https://stackoverflow.com/questions/4201959
复制相似问题