Как собственно это реализовать? Вопрос в рунете совсем не освещен. Отдельно на View я могу динамически менять размер WebView, но в ячейке что то не получается, размер TableViewCell не могу изменить
Динамическое изменение размера WebView и TableViewCell когда WebView внутри TableViewCell
динамическая таблица ? func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
<#code#>
}
или может через проперти tableView.estimatedRowHeight = 1000
в ViewDidLoad надо прописать
tableView.estimatedRowHeight = высота ячейки
tableView.rowHeight = UITableViewAutomaticDimension
это есть, у меня 7 типов ячеек. как сделать чтоб код swift подсвечивался? на каком ресурсе? код хочу вставить. И странно, почему на форуме нет ответа с цитированием…
estimatedHeightForRowAt тоже не получается завести, ошибки сыпет
p.s. изучаю swift с ноября
например, когда по курсу создавал проект, для динамического изменение размера ячеек, надо было в attribute inspector, значение line установить на 0, после, в ViewDidLoad прописать [quote=“saslanbek, post:3, topic:3018”]
tableView.estimatedRowHeight = высота ячейки
tableView.rowHeight = UITableViewAutomaticDimension
[/quote]
import UIKit
extension ConversationDetailViewController {
static func create() -> ConversationDetailViewController {
return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: identifier) as! ConversationDetailViewController
}
}
class ConversationDetailViewController: UIViewController, UIWebViewDelegate, UITableViewDelegate{
fileprivate let htmlDetailCellIdentifier = "HtmlDetailCell"
var contentHeights : [CGFloat] = [0.0, 0.0]
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 44
self.tableView.rowHeight = UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.modelsArray.count
}
private func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "TextDetailCell2")
if self.modelsArray[(indexPath as NSIndexPath).row].file_name.characters.count == 0 && self.modelsArray[(indexPath as NSIndexPath).row].type == isHaveCheckBox.No.rawValue {
return createHtmlDetailCell(indexPath)
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath, animated: true)
}
fileprivate func createHtmlDetailCell(_ indexPath: IndexPath) -> HtmlDetailCell {
let cell = tableView.dequeueReusableCell(withIdentifier: htmlDetailCellIdentifier) as! HtmlDetailCell
let htmlString:String! = modelsArray[(indexPath as NSIndexPath).row].text as String
let htmlHeight = contentHeights[indexPath.row]
cell.htmlView.tag = indexPath.row
cell.htmlView.delegate = self
cell.htmlView.loadHTMLString(htmlString, baseURL: nil)
cell.htmlView.frame = CGRect(x:0, y:0, width:cell.frame.size.width, height:htmlHeight)
return cell
}
func webViewDidFinishLoad(_ webView: UIWebView) {
if (contentHeights[webView.tag] != 0.0)
{
return
}
contentHeights[webView.tag] = webView.scrollView.contentSize.height
tableView.reloadRows(at: [NSIndexPath(row: webView.tag, section: 7) as IndexPath], with: .automatic)
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return contentHeights[indexPath.row]
}
}
мда… что то не очень читабельно
вот такая ошибка “Messenger was compiled with optimization - stepping may behave oddly; variables may not be available.” и bad instruction при return из estimatedHeightForRowAt
self.tableView.estimatedRowHeight = 44
self.tableView.rowHeight = UITableViewAutomaticDimension
уберите ети строчки
и я чуть не тот наверное метод написал вам - estimatedHeightForRowAt - там просто heightForRowAt
И проверте что действительно записано в contentHeights[webView.tag] = webView.scrollView.contentSize.height тут и в самом массиве contentHeights
это есть, у меня 7 типов ячеек. как сделать чтоб код swift подсвечивался? - ето настройки цвета или у вас автопредложение методови переменних не работает ? - тут перезапуск Xcode поможет
Просто выделите ту, часть которую хотите цитировать и нажмите ответить. Цитата вставится автоматически.
Мне кажется один в один вопрос на stackoverflow.
Это уже ответ:
class TableViewController: UITableViewController, UIWebViewDelegate
{
var content : [String] = ["test1<br>test1<br>test1<br>test1<br>test1<br>test1", "test22<br>test22<br>test22<br>test22<br>test22<br>test22"]
var contentHeights : [CGFloat] = [0.0, 0.0]
// ...
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("newsCell", forIndexPath: indexPath) as! NewsTableViewCell
let htmlString = content[indexPath.row]
let htmlHeight = contentHeights[indexPath.row]
cell.webView.tag = indexPath.row
cell.webView.delegate = self
cell.webView.loadHTMLString(htmlString, baseURL: nil)
cell.webView.frame = CGRectMake(0, 0, cell.frame.size.width, htmlHeight)
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return contentHeights[indexPath.row]
}
func webViewDidFinishLoad(webView: UIWebView)
{
if (contentHeights[webView.tag] != 0.0)
{
// we already know height, no need to reload cell
return
}
contentHeights[webView.tag] = webView.scrollView.contentSize.height
tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: webView.tag, inSection: 0)], withRowAnimation: .Automatic)
}
// ...
}
Значит у Вас какая-то ошибка с индексами. То есть нумерация элементов некорректная раз out of range.
какой вопрос ? в чем проблема ? Когда делаеш через ViewController - то нада только делегат и датасор подключить
посмотрите мой код - делагат ВебВью 66 строчка
когда доходит до визова обновить - там может бить уже другое значение
Датасорс и делегати - подтягнуть на сториборде ( желтая иконка)