let htmlString = "<html><body><img src='image1.jpg'><img src='image2.jpg'></body></html>"
let modifiedHtmlString = htmlString.replacingOccurrences(of: "<img", with: "<img width='100' height='100'")
print(modifiedHtmlString)
let webView = WKWebView(frame: view.bounds)
webView.loadHTMLString(modifiedHtmlString, baseURL: nil)
webView.navigationDelegate = self
view.addSubview(webView)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(imageTapped))
webView.addGestureRecognizer(tapGesture)
let modifiedHtmlString = htmlString.replacingOccurrences(of: "<img", with: "<img width='100' height='100'")
swift 如何给html字符串里所有的图片标签更改宽高
You can add a tap gesture recognizer to the UITextView and then use the location of the tap to determine which image was tapped. Once you have the image, you can perform whatever action you want. Here's an example:
#点击UITextView
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(imageTapped))
textView.addGestureRecognizer(tapGesture)
@objc func imageTapped(sender: UITapGestureRecognizer) {
let textView = sender.view as! UITextView
let layoutManager = textView.layoutManager
// location of tap in textView coordinates and taking the inset into account
var location = sender.location(in: textView)
location.x -= textView.textContainerInset.left
location.y -= textView.textContainerInset.top
// character index at tap location
let characterIndex = layoutManager.characterIndex(for: location, in: textView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
// if index is within an image range, do something
for attachment in textView.textStorage.attachments {
if let range = attachment.range, NSLocationInRange(characterIndex, range) {
// do something with the image attachment
print("Image tapped")l
break
}
}
}
# 获取attachment 图片
for attachment in textView.textStorage.attachments {
let image = attachment.image(forBounds: attachment.bounds, textContainer: textView.textContainer, characterIndex: attachment.characterIndex)
// do something with the image
print("Image retrieved")
}
# 获取attachment 路径
leet attachmentPath = NSTemporaryDirectory() + attachment.fileWrapper.preferredFilename
print(attachmentPath)
let htmlString = "<html><body><img src='localImage.jpg'></body></html>"
let baseUrl = Bundle.main.bundleURL
webView.loadHTMLString(htmlString, baseURL: baseUrl)
let scrollView = UIScrollView(frame: view.bounds)
let imageView = UIImageView(image: UIImage(named: "image1.jpg"))
imageView.contentMode = .scaleAspectFit
scrollView.addSubview(imageView)
scrollView.contentSize = imageView.bounds.size
scrollView.maximumZoomScale = 3.0
scrollView.minimumZoomScale = 1.0
scrollView.delegate = self
view.addSubview(scrollView)
extension ViewController: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return scrollView.subviews.first
}
}
关于textview给富文本图片增加点击事件
最新推荐文章于 2024-09-11 19:47:57 发布