【发布时间】:2020-07-21 12:36:12
【问题描述】:
我自定义标题视图,在其中添加图像和标签,我知道我想让它可点击,但它不起作用。我在标题视图中添加了点击手势,但它不起作用。
这是我的代码。
func navTitleWithImageAndText(titleText: String,subTitleText:String, imageName: String) -> UIView {
// Creates a new UIView
let titleView = UIView()
let label = UILabel(frame: CGRect(x: 0, y: -15, width: 0, height: 0))
// Creates a new text label
// let label = UILabel()
label.text = titleText
label.font = UIFont.boldSystemFont(ofSize: 17)
//label.center = titleView.center
label.textColor = .white
//label.textAlignment = NSTextAlignment.center
label.sizeToFit()
let subtitleLabel = UILabel(frame: CGRect(x: 0, y: 5, width: 0, height: 0))
subtitleLabel.backgroundColor = UIColor.clear
subtitleLabel.textColor = UIColor.white
subtitleLabel.font = UIFont.systemFont(ofSize: 12)
subtitleLabel.text = subTitleText
subtitleLabel.sizeToFit()
// Creates the image view
let image = UIImageView()
image.image = UIImage(named: imageName)
// Maintains the image's aspect ratio:
let imageAspect = image.image!.size.width / image.image!.size.height
// Sets the image frame so that it's immediately before the text:
let imageX = label.frame.origin.x - label.frame.size.height * imageAspect - 20
let imageY = label.frame.origin.y
let imageWidth = label.frame.size.height * imageAspect + 15
let imageHeight = label.frame.size.height + 15
image.frame = CGRect(x: imageX, y: imageY, width: imageWidth, height: imageHeight)
image.contentMode = UIView.ContentMode.scaleAspectFit
// Adds both the label and image view to the titleView
titleView.addSubview(label)
titleView.addSubview(image)
titleView.addSubview(subtitleLabel)
// Sets the titleView frame to fit within the UINavigation Title
titleView.sizeToFit()
return titleView
}
在其中添加点击手势。但为什么它不起作用。
titleView.addGestureRecognizer(titleGestureRecognizer)
【问题讨论】:
-
你为什么不使用
UIButton?当不用作标题视图而是用作简单视图时,您的代码是否有效? -
@DávidPásztor 添加了 UIbutton 但仍然无法正常工作。
-
如果您只是在
UIViewController上使用相同的视图,而不是作为导航栏上的标题视图,它是否有效?通过测试,您可以检查问题是出在您的视图还是您将其添加为标题视图的方式(顺便说一句,您没有包括在问题中)。 -
我认为您的视图位于标题、副标题和图像视图的后面,这就是它无法点击的原因。您必须在标题标签上添加一个手势。
-
@DávidPásztor 我正在使用相同的点击手势,它工作正常。当我添加 self.navigationController?.navigationBar.addGestureRecognizer(titleGestureRecognizer) 它也可以工作,但是当我点击后退按钮时它也会调用。
标签: ios swift navigation