我有一个tableViewController,在第一个单元格中,我用showMore / ShowLess按钮放置了一个textView。就像在这个答案中:How to add a Show More/Show Less UIButton to control UITextView。 我的问题是:当用户单击showMore按钮并单击showLess时,如何更新约束? 我有2个类,一个叫:TableViewController,另一个叫TableViewControllerCell。
class TableViewControllerCell: UITableViewCell, UITextViewDelegate {
@IBOutlet weak var descriptionTextView: UITextView!
@IBOutlet weak var seeMoreButtonO: UIButton!
var heightConstraint:CGFloat = 50 // I don't know how to implement the constraint value
override func awakeFromNib() {
super.awakeFromNib()
}
func getRowHeightFromText(strText : String!) -> CGFloat
{
let textView : UITextView! = UITextView(frame: CGRect(x: descriptionTextView.frame.origin.x,y: 0,width: descriptionTextView.frame.size.width,height: 0))
textView.text = strText
textView.font = UIFont(name: "Fira Sans", size: 16.0)
textView.sizeToFit()
var txt_frame : CGRect! = CGRect()
txt_frame = textView.frame
var size : CGSize! = CGSize()
size = txt_frame.size
size.height = 50 + txt_frame.size.height
return size.height
}
@IBAction func showMoreButton(_ sender: UIButton) {
if sender.tag == 0 {
let height = self.getRowHeightFromText(strText: self.descriptionTextView.text)
self.heightConstraint = height
self.layoutIfNeeded()
seeMoreButtonO.setTitle("ShowLess", for: .normal)
sender.tag = 1
} else {
self.heightConstraint = 116
self.layoutIfNeeded()
seeMoreButtonO.setTitle("ShowMore", for: .normal)
sender.tag = 0
}
}
}
答案 0 :(得分:0)
保留约束IBOutlet并更新值,但是如果您具有uitableview,我建议使用tableview自己的方法,例如
1-如果要保持单元格显示较少,请在heightoftablviewcell中将某个常数的单元格高度设置为50 2-一旦点击以显示更多更新您的单元格高度,您可以跟踪模型/ dic中个别情况下每个单元格的高度
答案 1 :(得分:0)
为约束创建出口,并设置所需的值,如下所示:
@IBOutlet weak var seeMoreConstraint: NSLayoutConstraint!
在您要更新约束的地方:
UIView.animate(withDuration: 0.1, animations: { () -> Void in
seeMoreConstraint.constant = /* Desired value, for example 50.0 */
self.view.setNeedsLayout() /* This tells the UI to update */
self.view.layoutIfNeeded()
})