Ios 注释单元格为’;t在发布评论后自动调整大小
在发布评论后,我很难让我的评论单元格正确调整大小 当注释视图首次加载时,一切看起来都很好 但是,在发布注释后,单元格仍保留其以前的大小,不会自动调整大小 这会导致新的注释单元格具有错误的尺寸(参见图片):Ios 注释单元格为’;t在发布评论后自动调整大小,ios,swift,autolayout,Ios,Swift,Autolayout,在发布评论后,我很难让我的评论单元格正确调整大小 当注释视图首次加载时,一切看起来都很好 但是,在发布注释后,单元格仍保留其以前的大小,不会自动调整大小 这会导致新的注释单元格具有错误的尺寸(参见图片): 第一次加载时的注释视图。注释单元格大小正确 即将发布一行注释 哦,不是:新的评论已经发布了,但是使用了旧的单元格大小 注释单元格的自动布局约束在情节提要中完成 注释文本视图的numberOfLines属性设置为0 在CommentViewController中,使用了Estimat
注释单元格的自动布局约束在情节提要中完成 注释文本视图的numberOfLines属性设置为0
在CommentViewController中,使用了EstimateDrowEight和automaticDimension:
self.tableView.estimatedRowHeight = 77
self.tableView.rowHeight = UITableView.automaticDimension
编辑:也使用layoutIfNeeded()
在CommentTableViewCell类中,调用prepareForReuse:
override func prepareForReuse()
{
super.prepareForReuse()
}
发布新注释后,拖动以刷新不会重新调整单元格大小。解决此问题的唯一方法是单击“上一步”按钮并重新进入“注释”视图
如何解决此问题?
谢谢你抽出时间
编辑:添加了我的故事板、继承人制度和约束的屏幕截图
编辑:更新了约束条件,使注释标签变为紫色以显示可见性 显示名称标签顶部到内容视图顶部 注释标签顶部到显示名称标签底部 注释标签底部到内容视图底部 将紫色添加到背景中,以更清楚地显示正在发生的事情 重新加载注释后,注释单元格约束无法正确调整以适应注释。如何解决此问题? 谢谢你抽出时间
最终编辑:删除不必要的代码并在评论中发布我的解决方案让我们从简单一点开始。。。与其处理
API
类,不如使用一个数组,让表单元格正常工作
这是一个视图控制器
- 文本字段和顶部的“发送”按钮(因此我们暂时不必担心键盘)
- 约束在文本字段下方的表视图
- 原型细胞
class CommentsCell: UITableViewCell {
@IBOutlet var userLabel: UILabel!
@IBOutlet var commenterLabel: UILabel!
@IBOutlet var timeLabel: UILabel!
@IBOutlet var commentLabel: UILabel!
}
现在,我们将为示例数据创建一个简单的struct
:
struct CommentStruct {
var userID: String = ""
var commenterID: String = ""
var commentTime: String = ""
var commentText: String = ""
}
下面是我们将用于view controller类的内容-我已经保留了您的通用代码流,尽管目前我们对它做的不多:
class CommentsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var commentTextField: UITextField!
@IBOutlet var tableView: UITableView!
var comments: [CommentStruct] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
tableView.separatorStyle = .none
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let c = tableView.dequeueReusableCell(withIdentifier: "commentsCell", for: indexPath) as! CommentsCell
// get the data
let cs = comments[indexPath.row]
// set text for labels in the cell
c.userLabel.text = cs.userID
c.commenterLabel.text = cs.commenterID
c.timeLabel.text = cs.commentTime
c.commentLabel.text = cs.commentText
return c
}
// Actions performed when the Send button is pressed
@IBAction func sendButton_TouchUpInside(_ sender: UIButton)
{
// Post the comment
self.postComment()
}
// This function posts a comment
func postComment()
{
// Store the comment text
// make sure text was entered
guard let commentText = self.commentTextField.text,
!commentText.isEmpty
else {
return
}
let cs = CommentStruct(userID: "User1",
commenterID: "Commenter1",
commentTime: "1d",
commentText: commentText)
// insert this data to make it the new "top" comment
comments.insert(cs, at: 0)
// Hide keyboard
self.view.endEditing(true)
// Refresh the comment feed
self.refresh()
}
// This method refreshes comments in the comment feed
@objc func refresh()
{
// Retrieve comments from the database
loadComments()
}
// This method loads the comments for a post
func loadComments()
{
// here you would do your api call to get the comment data
// and re-populate your dataSource array
// Reload the table view data
self.tableView.reloadData()
// Unhide the images, views, text fields and buttons???
//self.unhideViewElements()
}
}
运行此操作时,输入的每个注释都将插入到数据源数组的开头,因此新注释将显示在顶部:
试试看。。。当您看到单元格大小正确时,请将此结构与API数据存储集成
以下是故事板的来源,您可以仔细查看:
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="17701" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="kqQ-83-E1D">
<device id="retina4_7" orientation="portrait" appearance="light"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17703"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="System colors in document resources" minToolsVersion="11.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--Comments View Controller-->
<scene sceneID="vQJ-Cm-Kfe">
<objects>
<viewController id="kqQ-83-E1D" customClass="CommentsViewController" customModule="DrawingTutorial" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="LfR-oh-wEI">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="ReB-5o-kkD">
<rect key="frame" x="0.0" y="62" width="375" height="585"/>
<color key="backgroundColor" systemColor="systemBackgroundColor"/>
<prototypes>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" reuseIdentifier="commentsCell" rowHeight="101" id="NdF-XY-hNL" customClass="CommentsCell" customModule="DrawingTutorial" customModuleProvider="target">
<rect key="frame" x="0.0" y="28" width="375" height="101"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="NdF-XY-hNL" id="eLj-wx-ThB">
<rect key="frame" x="0.0" y="0.0" width="375" height="101"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="person.circle" catalog="system" translatesAutoresizingMaskIntoConstraints="NO" id="WoV-fE-nM7">
<rect key="frame" x="16" y="11.5" width="40" height="39"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstAttribute="width" constant="40" id="Duy-4K-awo"/>
<constraint firstAttribute="width" secondItem="WoV-fE-nM7" secondAttribute="height" multiplier="1:1" id="s3a-Ri-9u1"/>
</constraints>
</imageView>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="252" verticalHuggingPriority="252" text="Display Name" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="OMA-aF-mTL">
<rect key="frame" x="64" y="11" width="105" height="21"/>
<color key="backgroundColor" red="0.45009386540000001" green="0.98132258650000004" blue="0.4743030667" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" numberOfLines="0" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="lII-cx-Qfb">
<rect key="frame" x="64" y="36" width="295" height="54"/>
<color key="backgroundColor" red="0.45138680930000002" green="0.99309605359999997" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="username" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="H3q-YO-OPD">
<rect key="frame" x="177" y="12.5" width="68" height="18"/>
<color key="backgroundColor" red="0.99953407049999998" green="0.98835557699999999" blue="0.47265523669999998" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<fontDescription key="fontDescription" type="italicSystem" pointSize="15"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="time" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="el2-VE-HXg">
<rect key="frame" x="332.5" y="14.5" width="26.5" height="16"/>
<color key="backgroundColor" red="1" green="0.83234566450000003" blue="0.47320586440000001" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<fontDescription key="fontDescription" type="system" pointSize="13"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstAttribute="bottomMargin" secondItem="lII-cx-Qfb" secondAttribute="bottom" id="77z-al-5f6"/>
<constraint firstItem="WoV-fE-nM7" firstAttribute="top" secondItem="eLj-wx-ThB" secondAttribute="topMargin" id="EBj-fZ-KPe"/>
<constraint firstItem="H3q-YO-OPD" firstAttribute="firstBaseline" secondItem="OMA-aF-mTL" secondAttribute="firstBaseline" id="He3-PN-s3Q"/>
<constraint firstItem="lII-cx-Qfb" firstAttribute="leading" secondItem="WoV-fE-nM7" secondAttribute="trailing" constant="8" id="J5m-6F-mMX"/>
<constraint firstItem="OMA-aF-mTL" firstAttribute="leading" secondItem="WoV-fE-nM7" secondAttribute="trailing" constant="8" id="OUd-aN-EpF"/>
<constraint firstAttribute="trailingMargin" secondItem="lII-cx-Qfb" secondAttribute="trailing" id="RiF-g5-Kqn"/>
<constraint firstItem="el2-VE-HXg" firstAttribute="firstBaseline" secondItem="H3q-YO-OPD" secondAttribute="firstBaseline" id="Ugz-tb-PDS"/>
<constraint firstItem="WoV-fE-nM7" firstAttribute="leading" secondItem="eLj-wx-ThB" secondAttribute="leadingMargin" id="WVE-gb-IZ3"/>
<constraint firstItem="H3q-YO-OPD" firstAttribute="leading" secondItem="OMA-aF-mTL" secondAttribute="trailing" constant="8" id="dpO-0E-5EY"/>
<constraint firstAttribute="trailingMargin" secondItem="el2-VE-HXg" secondAttribute="trailing" id="lj2-pU-CEd"/>
<constraint firstItem="lII-cx-Qfb" firstAttribute="top" secondItem="OMA-aF-mTL" secondAttribute="bottom" constant="4" id="tPn-WG-oP5"/>
<constraint firstItem="OMA-aF-mTL" firstAttribute="top" secondItem="WoV-fE-nM7" secondAttribute="top" id="uLn-3z-aWP"/>
</constraints>
</tableViewCellContentView>
<color key="backgroundColor" red="0.46202266219999999" green="0.83828371759999998" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<connections>
<outlet property="commentLabel" destination="lII-cx-Qfb" id="e6K-Oh-9GU"/>
<outlet property="commenterLabel" destination="H3q-YO-OPD" id="vrd-FX-yk9"/>
<outlet property="timeLabel" destination="el2-VE-HXg" id="tjS-KJ-azE"/>
<outlet property="userLabel" destination="OMA-aF-mTL" id="n2P-vl-MLU"/>
</connections>
</tableViewCell>
</prototypes>
</tableView>
<textField opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="9T9-jd-9hp">
<rect key="frame" x="8" y="8" width="291" height="34"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits"/>
</textField>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="npH-eO-rmF">
<rect key="frame" x="307" y="10" width="60" height="30"/>
<constraints>
<constraint firstAttribute="width" constant="60" id="IqL-gO-uY2"/>
</constraints>
<state key="normal" title="Send"/>
<connections>
<action selector="sendButton_TouchUpInside:" destination="kqQ-83-E1D" eventType="touchUpInside" id="cFF-G9-YEj"/>
</connections>
</button>
</subviews>
<viewLayoutGuide key="safeArea" id="7k7-br-c0C"/>
<color key="backgroundColor" systemColor="systemBackgroundColor"/>
<constraints>
<constraint firstItem="7k7-br-c0C" firstAttribute="trailing" secondItem="ReB-5o-kkD" secondAttribute="trailing" id="BpD-NC-I8a"/>
<constraint firstItem="7k7-br-c0C" firstAttribute="bottom" secondItem="ReB-5o-kkD" secondAttribute="bottom" constant="20" id="LZX-74-J2l"/>
<constraint firstItem="ReB-5o-kkD" firstAttribute="leading" secondItem="7k7-br-c0C" secondAttribute="leading" id="MrF-Ev-h4l"/>
<constraint firstItem="9T9-jd-9hp" firstAttribute="top" secondItem="7k7-br-c0C" secondAttribute="top" constant="8" id="WSE-8f-4vd"/>
<constraint firstItem="9T9-jd-9hp" firstAttribute="leading" secondItem="7k7-br-c0C" secondAttribute="leading" constant="8" id="dOf-rz-39l"/>
<constraint firstItem="npH-eO-rmF" firstAttribute="centerY" secondItem="9T9-jd-9hp" secondAttribute="centerY" id="iKO-JR-FeT"/>
<constraint firstItem="npH-eO-rmF" firstAttribute="leading" secondItem="9T9-jd-9hp" secondAttribute="trailing" constant="8" id="tFt-L3-xDM"/>
<constraint firstItem="7k7-br-c0C" firstAttribute="trailing" secondItem="npH-eO-rmF" secondAttribute="trailing" constant="8" id="xTY-Wm-wIc"/>
<constraint firstItem="ReB-5o-kkD" firstAttribute="top" secondItem="9T9-jd-9hp" secondAttribute="bottom" constant="20" id="yR9-xm-4XE"/>
</constraints>
</view>
<connections>
<outlet property="commentTextField" destination="9T9-jd-9hp" id="oiN-nx-d3k"/>
<outlet property="tableView" destination="ReB-5o-kkD" id="0h3-yw-Kt7"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="MMl-5e-W3I" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="368.80000000000001" y="795.6521739130435"/>
</scene>
</scenes>
<resources>
<image name="person.circle" catalog="system" width="128" height="121"/>
<systemColor name="systemBackgroundColor">
<color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</systemColor>
</resources>
</document>
// Set the number of lines for the comment label
cell.commentLabel.numberOfLines = cell.commentLabel.calculateMaxLines()
// Set the height constraint to numberOfLines * 17
cell.commentLabelHeightConstraint.constant = CGFloat(cell.commentLabel.numberOfLines) * 17)
// Layout the cell
cell.contentView.layoutIfNeeded()