我有一个UITextField
组件,该组件的右侧有一个图标。图标只是一个UIImageView
。我正在尝试使用以下代码为UIImageView
插入图片
imageView.image = UIImage(named: "example")?.withAlignmentRectInsets(UIEdgeInsets(top: -4, left: 0, bottom: -4, right: 0))
但是,它不起作用,因为设置“图像”时未设置框架。我在下面的代码中给出它的框架;
iconImageView.frame = CGRect(
x: bounds.size.width - iconWidth - iconMarginLeft,
y: bounds.size.height - textHeight() - iconMarginBottom,
width: iconWidth,
height: textHeight()
)
以及我如何设置UIImageView
fileprivate func createIconImageView() {
let iconImageView = UIImageView()
iconImageView.backgroundColor = .clear
iconImageView.contentMode = .scaleAspectFill
iconImageView.autoresizingMask = [.flexibleTopMargin, .flexibleRightMargin]
if (hasToolTip) {
let tapGesture = UITapGestureRecognizer(target: self, action:#selector(toolTipTapped(_:)))
iconImageView.addGestureRecognizer(tapGesture)
iconImageView.isUserInteractionEnabled = true
let image = UIImage(named: "infotooltip")
image?.accessibilityIdentifier = "tooltipImage"
iconImageView.image = image!
changeIconAlphaToOne()
self.iconImageView = iconImageView
} else {
self.iconImageView = iconImageView
changeIconAlphaToZero()
}
addSubview(iconImageView)
}
我的问题是,我需要给图像添加UIEdgeInset
。但是,由于我试图在设置框架之前先给它,所以它不起作用。我该如何实现?
我也尝试通过参考下面的帖子来调整图像大小,但不适用于我。我也不想将其放在内容视图中,这会使我的组件类更加复杂。 The simplest way to resize an UIImage?