以编程方式添加UITableView

时间:2016-05-19 10:39:16

标签: ios swift uitableview dynamic

我想我已经查看过像我这样的很多问题,但似乎没什么用。

我正在向服务器发送请求,当我获得所有数据时,我开始以编程方式填充ViewController。所有这些都发生在main_queue

这是添加表格的代码:

if  self.attachments.count > 0 {
        docTableView = UITableView(frame: CGRect(x: 0.0, y: 0.0, width: self.myView.frame.width, height: 500.0), style: UITableViewStyle.Plain)
        docTableView!.translatesAutoresizingMaskIntoConstraints = false
        docTableView!.registerNib(UINib(nibName: "MenuCell", bundle: nil), forCellReuseIdentifier: "MenuCell")
        self.myView.addSubview(docTableView!)
        docTableView!.dataSource = self
        docTableView!.delegate = self

        self.myView.addConstraint(NSLayoutConstraint(item: docTableView!, attribute: .Top, relatedBy: .Equal, toItem: subviews!.last, attribute: .Bottom, multiplier: 1.0, constant: 5.0))
        self.myView.addConstraint(NSLayoutConstraint(item: docTableView!, attribute: .Leading, relatedBy: .Equal, toItem: self.headerStackView, attribute: .Leading, multiplier: 1.0, constant: 0))

        self.docTableView?.reloadData()
        subviews?.append(docTableView!)
    }

然后,我意识到已经调用了两种方法:numberOfRowsInSectionheightForRowAtIndexPath甚至元素的数量大于0。 但cellForRowAtIndexPath没有被调用,我想这就是我根本看不到tableView的原因。 那我该怎么做呢?

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if tableView == self.docTableView {
         return attachments.count
    }
    else {
        return self.notificationViewModel!.comments.count
    }

}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 100.0 // I add this to show that its not zero
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if tableView == self.docTableView {
        let object = attachments[indexPath.row]
        UIApplication.sharedApplication().openURL(NSURL(string: object.Url!)!)

    }
}

因此commTableViewdocTableView相同。我需要他们两个,他们也有同样的问题。

编辑:我有这种层次结构:View->ScrollView->myView

EDIT2:我的ViewController代码。我要添加不同类型的数据,但所有数据都需要附件和注释表

class NotificationViewController: UIViewController, MarkChosenDelegate, UITableViewDataSource, UITableViewDelegate {

//IBOutlets FROM STORYBOARD
@IBOutlet weak var myView: UIView!

@IBOutlet weak var headerStackView: UIStackView!
@IBOutlet weak var setMarkButton: UIButton!
@IBOutlet weak var placingWayCodeLabel: UILabel!
@IBOutlet weak var leftDaysLabel: UILabel!
@IBOutlet weak var typeLabel: UILabel!
@IBOutlet weak var regionLabel: UILabel!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var notificationNameLabel: UILabel!
@IBOutlet weak var markColorButton: UIButton!

var docTableView:UITableView?
var commTableView:UITableView?

var delegate:NewMarkSetProtocol?

var notificationViewModel: NotificationViewModel?

var attachments:[Attachment] = []

//FIELDS FOR SEGUE TO THE CUSTOMER
var customerGuid:String?
var customerName:String?
var inn:String?
var kpp:String?

let marks = DataClass.sharedInstance.marks

var viewUtils:ViewUtils?

var notificationItem: NotificationT? {
    didSet {
        self.setUpTheHeaderInformation()
    }
}

//VIEW CONTROLLER LIFE CYCLES METHODS
override func viewDidLoad() {
    super.viewDidLoad()

    self.setUpTheHeaderInformation()

    viewUtils = ViewUtils()
    viewUtils?.showActivityIndicator(self.view)

    notificationViewModel = NotificationViewModel()
    notificationViewModel?.delegateComments = self
    notificationViewModel?.delegateInformation = self
    if (notificationItem != nil) {
        if UsefulClass.isConnectedToNetwork() == true {
            notificationViewModel!.getNotification(notificationItem!)
            notificationViewModel!.getComments((notificationItem?.NotificationGuid)!)
        } else {
            notificationViewModel!.getCoreNotification(notificationItem!)
        }
    }
    print(setMarkButton)

}

func setUpTheHeaderInformation() {

    if let notificationT = self.notificationItem {
        self.navigationItem.title = notificationT.OrderName
        self.notificationItem?.IsRead = true

        if let label = self.notificationNameLabel {
            label.text = notificationT.OrderName
            self.placingWayCodeLabel.text = notificationT.getPlacingWayId()
            self.leftDaysLabel.text = notificationT.getLeft()
            self.typeLabel.text = notificationT.getType()

            if (marks.count != 0) {
                var mark:MarkClass?

                for i in 0..<marks.count {
                    if (marks[i].Id == notificationT.MarkId) {
                        mark = marks[i]
                    }
                }

                if let _mark = mark {
                    self.setMarkButton.setTitle(String(_mark.Name!), forState: .Normal)
                    self.markColorButton.hidden = false
                    self.markColorButton.backgroundColor = UsefulClass.colorWithHexString(_mark.Color!)
                } else {
                    self.markColorButton.hidden = true
                }
            }
            if let code = notificationT.RegionCode {
                self.regionLabel.text = UsefulClass.regionByRegionCode(code)
            }
        }
    }
}


//TABLE VIEW
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let count:Int = 2
    if tableView == self.docTableView {
        print(attachments.count)
        return attachments.count
    }
    if tableView == self.commTableView {
        return self.notificationViewModel!.comments.count
    }
    return count
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 100.0
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if tableView == self.docTableView {
        let object = attachments[indexPath.row]
        UIApplication.sharedApplication().openURL(NSURL(string: object.Url!)!)
    }
}


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    if tableView == self.docTableView {
        let cell = tableView.dequeueReusableCellWithIdentifier("MenuCell", forIndexPath: indexPath) as! MenuCell
        let object = attachments[indexPath.row]
        let endIndex = object.FileName!.endIndex.advancedBy(-4)
        let type:String = (object.FileName?.substringFromIndex(endIndex))!
        cell.imageMark.image = notificationViewModel!.getImageForAttachment(type)
        cell.name.text = object.FileName
        cell.count.text = ""

        return cell
    } else  {
        let cell = tableView.dequeueReusableCellWithIdentifier("CommentItemCell", forIndexPath: indexPath) as! CommentTableViewCell
        let object = self.notificationViewModel!.comments[indexPath.row]
        if let name = object.getCreatorName() {
            cell.nameUser.text = name
        }
        cell.textComment.text = object.Text
        //cell.imageUser.image =
        cell.timeComment.text = object.getTime()
        return cell
    }
}

func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    if tableView == self.commTableView {
        return true
    } else {
        return false
    }
}


func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        Requests.deleteComment(notificationViewModel!.comments[indexPath.row].Id!, notificationGuid: (self.notificationItem?.NotificationGuid)!)
        notificationViewModel?.comments.removeAtIndex(indexPath.row)
        self.commTableView!.reloadData()
    } else {

    }
}

extension String {
func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
    let constraintRect = CGSize(width: width, height: CGFloat.max)

    let boundingBox = self.boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

    return boundingBox.height
}
}

 extension NSAttributedString {
func heightWithConstrainedWidth(width: CGFloat) -> CGFloat {
    let constraintRect = CGSize(width: width, height: CGFloat.max)
    let boundingBox = self.boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil)

    return ceil(boundingBox.height)
}

func widthWithConstrainedHeight(height: CGFloat) -> CGFloat {
    let constraintRect = CGSize(width: CGFloat.max, height: height)

    let boundingBox = self.boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil)

    return ceil(boundingBox.width)
}
}

extension NotificationViewController:NotificationInformationUpdate {

func informationUpdate() {

    var subviews:[UIView]? = [UIView]()

    switch(notificationItem?.Type)! {
    case 0:

        let notification  = notificationViewModel?.notification as! Notification_223
        self.attachments = notification.attachments
        if let name = notification.TenderPlanOrganisationName {
            subviews = addTitleandValue("Заказчик", _value: name, _subviews: subviews!, numberOfLines: 0)
        }

        if let initialSum = notification.InitialSum {
            subviews = addTitleandValue("Цена контракта", _value: initialSum, _subviews: subviews!, numberOfLines: 0)
        } else if let maxPrice = notificationItem?.MaxPrice {
            subviews = addTitleandValue("Цена контракта", _value: UsefulClass.getMaxPrice(maxPrice), _subviews: subviews!, numberOfLines: 0)
        }

        break
    case 1:
        let notification = notificationViewModel?.notification as! Notification_44
        self.attachments = notification.attachments!
        let customerNameTitle = UILabel()
        customerNameTitle.text = "Заказчик:"
        customerNameTitle.translatesAutoresizingMaskIntoConstraints = false
        customerNameTitle.textColor = UIColor.grayColor()
        setSimilarConstraintsToTitlesLabels(customerNameTitle,     relatedView: self.headerStackView)

        let customerName = UILabel()
        customerName.text = notification.TenderPlanOrganisationName
        customerName.textColor = UIColor.blueColor()
        customerName.userInteractionEnabled = true
        let tapGester = UITapGestureRecognizer(target: self, action:     #selector(NotificationViewController.customerNameClick(_:)))
        customerName.addGestureRecognizer(tapGester)
        subviews = setSimilarConstraintsToValuesLabels(customerName,    relatedView: customerNameTitle, _subViews: subviews!)

        if let maxprice = notificationItem?.MaxPrice {
            subviews = addTitleandValue("Цена контракта", _value: UsefulClass.getMaxPrice(maxprice), _subviews: subviews!, numberOfLines: 0)
        }

        break
    case 2:
        let notification = notificationViewModel?.notification as! B2BNotification
        self.attachments = notification.attachments
        subviews = addTitleandValue("Заказчик", _value: notification.TenderPlanOrganisationName!, _subviews: subviews!, numberOfLines: 0)

        if let priceTotal = notification.PriceTotal {
            var value = UsefulClass.getMaxPrice(priceTotal)
            if let pricevat = notification.PriceVAT {
                value.appendContentsOf(" (" +  pricevat + ")")
            }
            subviews = addTitleandValue("Начальная цена всего лота", _value: value, _subviews: subviews!, numberOfLines: 0)
        } else {
            subviews = addTitleandValue("Начальная цена всего лота", _value: "Отсутствует поле", _subviews: subviews!, numberOfLines: 0)
        }

        if let priceone = notification.PriceOne {
            subviews = addTitleandValue("Цена за единицу продукции", _value: UsefulClass.getMaxPrice(priceone), _subviews: subviews!, numberOfLines: 0)
        }
        break

    case 7, 17:

        let notification = notificationViewModel?.notification as! TakTorgNotification
        self.attachments = notification.attachments
        subviews = addTitleandValue("Наименование заказа", _value: notification.Subject!, _subviews: subviews!, numberOfLines: 0)

        if let procNumber = notification.ProcedureProcedureNumber {
            subviews = addTitleandValue("Номер закупки", _value: procNumber, _subviews: subviews!, numberOfLines: 0)
        } else if let procNumber2 = notification.ProcedureProcedureNumber2 {
            subviews = addTitleandValue("Номер закупки", _value: procNumber2, _subviews: subviews!, numberOfLines: 0)
        }

        if let startPrice = notification.StartPrice {
            subviews = addTitleandValue("Начальная цена", _value: UsefulClass.getMaxPrice(startPrice), _subviews: subviews!, numberOfLines: 0)
        }

        if let peretorgPossible = notification.ProcedurePeretorgPossible {
            subviews = addTitleandValue("Возможность проведения процедуры переторжки", _value: peretorgPossible, _subviews: subviews!, numberOfLines: 0)
        }

        if let negotiationPossible = notification.ProcedureNegotiationPossible {
            subviews = addTitleandValue("Возможность проведения переговоров", _value: negotiationPossible, _subviews: subviews!, numberOfLines: 0)
        }
        //….
        break
    default:
        break
    }


    let documentsTitle = UILabel()
    documentsTitle.text = "Документы закупки"
    documentsTitle.textColor = UIColor.blackColor()
    documentsTitle.translatesAutoresizingMaskIntoConstraints = false
    documentsTitle.font = documentsTitle.font.fontWithSize(18)
    self.myView.addSubview(documentsTitle)
    self.myView.addConstraint(NSLayoutConstraint(item: documentsTitle, attribute: .Top, relatedBy: .Equal, toItem: subviews!.last, attribute: .Bottom, multiplier: 1.0, constant: 12.0))
    self.myView.addConstraint(NSLayoutConstraint(item: documentsTitle, attribute: .Leading, relatedBy: .Equal, toItem: self.headerStackView, attribute: .Leading, multiplier: 1.0, constant: 0))
    subviews?.append(documentsTitle)
    if  self.attachments.count > 0 {
        docTableView = UITableView()
        docTableView!.translatesAutoresizingMaskIntoConstraints = false
        docTableView!.registerNib(UINib(nibName: "MenuCell", bundle: nil), forCellReuseIdentifier: "MenuCell")
        self.myView.addSubview(docTableView!)
        docTableView!.dataSource = self
        docTableView!.delegate = self
        self.myView.addConstraint(NSLayoutConstraint(item: docTableView!, attribute: .Top, relatedBy: .Equal, toItem: subviews!.last, attribute: .Bottom, multiplier: 1.0, constant: 5.0))
        self.myView.addConstraint(NSLayoutConstraint(item: docTableView!, attribute: .Leading, relatedBy: .Equal, toItem: self.headerStackView, attribute: .Leading, multiplier: 1.0, constant: 0))
        self.myView.addConstraint(NSLayoutConstraint(item: docTableView!, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 300.0))
        self.docTableView?.reloadData()
        subviews?.append(docTableView!)
    }

    if notificationViewModel?.comments.count > 0 {
        commTableView = UITableView()
        commTableView?.translatesAutoresizingMaskIntoConstraints = false
        commTableView!.registerNib(UINib(nibName: "CommentCell", bundle: nil), forCellReuseIdentifier: "CommentItemCell")
        self.myView.addSubview(commTableView!)
        self.myView.addConstraint(NSLayoutConstraint(item: commTableView!, attribute: .Top, relatedBy: .Equal, toItem: subviews!.last, attribute: .Bottom, multiplier: 1.0, constant: 5.0))
        self.myView.addConstraint(NSLayoutConstraint(item: commTableView!, attribute: .Leading, relatedBy: .Equal, toItem: self.headerStackView, attribute: .Leading, multiplier: 1.0, constant: 0))
        subviews?.append(commTableView!)
        commTableView?.dataSource = self
        commTableView?.delegate = self
    }

    //TITLE
    let addCommentLabel = UILabel()
    addCommentLabel.text = "Добавьте свой комментарий"
    addCommentLabel.translatesAutoresizingMaskIntoConstraints = false
    addCommentLabel.textColor = UIColor.lightGrayColor()
    self.myView.addSubview(addCommentLabel)
    self.myView.addConstraint(NSLayoutConstraint(item: addCommentLabel, attribute: .Top, relatedBy: .Equal, toItem: subviews!.last, attribute: .Bottom, multiplier: 1.0, constant: 10.0))
    self.myView.addConstraint(NSLayoutConstraint(item: addCommentLabel, attribute: .Leading, relatedBy: .Equal, toItem: self.headerStackView, attribute: .Leading, multiplier: 1.0, constant: 0))
    subviews?.append(addCommentLabel)

    let textField = UITextField()
    textField.translatesAutoresizingMaskIntoConstraints = false
    textField.borderStyle = .RoundedRect
    self.myView.addSubview(textField)
    self.myView.addConstraint(NSLayoutConstraint(item: textField, attribute: .Top, relatedBy: .Equal, toItem: subviews!.last, attribute: .Bottom, multiplier: 1.0, constant: 5.0))
    self.myView.addConstraint(NSLayoutConstraint(item: textField, attribute: .Leading, relatedBy: .Equal, toItem: self.headerStackView, attribute: .Leading, multiplier: 1.0, constant: 0))
    self.myView.addConstraint(NSLayoutConstraint(item: textField, attribute: .Width, relatedBy: .Equal, toItem: self.myView, attribute: .Width, multiplier: 1.0, constant: -15))
    subviews?.append(textField)

    let sendButton = UIButton()
    sendButton.setTitle("Отправить", forState: .Normal)
    sendButton.translatesAutoresizingMaskIntoConstraints = false
    sendButton.backgroundColor = UIColor.blueColor()
    sendButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
    self.myView.addSubview(sendButton)
    self.myView.addConstraint(NSLayoutConstraint(item: sendButton, attribute: .Top, relatedBy: .Equal, toItem: subviews!.last, attribute: .Bottom, multiplier: 1.0, constant: 5.0))
    self.myView.addConstraint(NSLayoutConstraint(item: textField, attribute: .Trailing, relatedBy: .Equal, toItem: textField, attribute: .Trailing, multiplier: 1.0, constant: 0))
    subviews?.append(sendButton)



    var height:CGFloat = 0.0
    for i in 0..<self.myView.subviews.count {
        height = height + myView.subviews[i].bounds.height
    }


    self.myView.frame = CGRect(x: 0, y: 0, width: self.myView.frame.width, height: self.myView.frame.height + height)
    self.view.frame = CGRect(x: 0, y: 0, width: self.myView.frame.width, height: self.view.frame.height + height)
    self.scrollView.frame = CGRect(x: 0, y: 0, width: self.myView.frame.width, height: self.scrollView.frame.height + height)
    self.scrollView.contentSize = CGSize(width: self.myView.frame.width, height: self.scrollView.frame.height + height)
    subviews  = nil
    self.viewUtils?.hideActivityIndicator(self.view)
}

func addPubDate(_subviews:[UIView], date:String, number:String) -> [UIView] {
    var subviews = _subviews
    let pubDateLabel = UILabel()
    pubDateLabel.text = "Дата публикации: " + UsefulClass.covertDataWithZ(date, withTime: false)
    pubDateLabel.translatesAutoresizingMaskIntoConstraints = false
    pubDateLabel.textColor = UIColor.blackColor()
    pubDateLabel.font = pubDateLabel.font.fontWithSize(11)
    self.myView.addSubview(pubDateLabel)
    self.myView.addConstraint(NSLayoutConstraint(item: pubDateLabel, attribute: .Top, relatedBy: .Equal, toItem: subviews.last, attribute: .Bottom, multiplier: 1.0, constant: 8.0))
    self.myView.addConstraint(NSLayoutConstraint(item: pubDateLabel, attribute: .Leading, relatedBy: .Equal, toItem: self.headerStackView, attribute: .Leading, multiplier: 1.0, constant: 0))
    subviews.append(pubDateLabel)
    notificationUrlNumber(subviews, relatedView: pubDateLabel, number: number)
    return subviews
}
func notificationUrlNumber(subviews:[UIView], relatedView:UILabel, number:String) {
    let label = UILabel()
    label.text = "Извещение №: " + number
    label.textColor = UIColor.blueColor()

    setSimilarConstraintsToValuesLabels(label, relatedView: relatedView, _subViews: subviews)
}


//левый заголовок для поля
func addtitle(_title:String, _subviews:[UIView]) -> [UIView] {
    var subviews = _subviews
    let title = UILabel()
    title.text = _title
    title.numberOfLines = 0
    title.textColor = UIColor.blackColor()
    title.translatesAutoresizingMaskIntoConstraints = false
    title.font = title.font.fontWithSize(18)
    self.myView.addSubview(title)
    self.myView.addConstraint(NSLayoutConstraint(item: title, attribute: .Top, relatedBy: .Equal, toItem: subviews.last, attribute: .Bottom, multiplier: 1.0, constant: 12.0))
    self.myView.addConstraint(NSLayoutConstraint(item: title, attribute: .Leading, relatedBy: .Equal, toItem: self.headerStackView, attribute: .Leading, multiplier: 1.0, constant: 0))
    subviews.append(title)
    return subviews

}

//правое значение для информационого поля
func addTitleandValue(_title:String, _value:String, _subviews:[UIView], numberOfLines:Int) -> [UIView] {
    var subviews = _subviews
    let title = UILabel()
    title.text = _title
    title.font = title.font.fontWithSize(12)
    if subviews.count > 0 {
        setSimilarConstraintsToTitlesLabels(title, relatedView: (subviews.last!))
    } else {
        setSimilarConstraintsToTitlesLabels(title, relatedView: self.headerStackView)
    }

    let value = UILabel()
    value.text = _value
    value.numberOfLines = numberOfLines
    value.font = value.font.fontWithSize(12)
    subviews = setSimilarConstraintsToValuesLabels(value, relatedView: title, _subViews: subviews)
    return subviews
}


func addBoolEptrfValues(_title:String, _subviews:[UIView])->[UIView] {
    var subviews = _subviews
    let title = UILabel()
    title.text = _title
    title.numberOfLines = 0
    setSimilarConstraintsToTitlesLabels(title, relatedView: (subviews.last!))

    let value = UILabel()
    value.text = notificationViewModel?.convertBoolToString(true)
    value.textColor = UIColor.blackColor()
    subviews = setSimilarConstraintsToValuesLabels(value, relatedView: title, _subViews: subviews)

    return subviews
}

func addDeleteButton(subviews:[UIView], isDeleted:Bool) -> UILabel {
    let deleteLabel = UILabel()
    if isDeleted == false {
        deleteLabel.text = "Удалить"
    } else {
        deleteLabel.text = "Восстановить"
    }
    deleteLabel.translatesAutoresizingMaskIntoConstraints = false
    deleteLabel.textColor = UIColor.blueColor()
    deleteLabel.font = deleteLabel.font.fontWithSize(11)
    self.myView.addSubview(deleteLabel)
    self.myView.addConstraint(NSLayoutConstraint(item: deleteLabel, attribute: .Top, relatedBy: .Equal, toItem: subviews.last, attribute: .Bottom, multiplier: 1.0, constant: 8.0))
    self.myView.addConstraint(NSLayoutConstraint(item: deleteLabel, attribute: .Leading, relatedBy: .Equal, toItem: self.headerStackView, attribute: .Leading, multiplier: 1.0, constant: 0))
    return deleteLabel
}


//right values next to the title
func setSimilarConstraintsToValuesLabels(subView:UILabel, relatedView:UILabel, _subViews:[UIView]) -> [UIView] {
    var subViews = _subViews
    subView.translatesAutoresizingMaskIntoConstraints = false
    self.myView.addSubview(subView)

    if (relatedView.text?.characters.count < 35 && subView.text?.characters.count < 30) {
        self.myView.addConstraint(NSLayoutConstraint(item: subView, attribute: .Right, relatedBy: .Equal, toItem: self.myView, attribute: .Right, multiplier: 1.0, constant: -15))
        self.myView.addConstraint(NSLayoutConstraint(item: subView, attribute: .Left, relatedBy: .Equal, toItem: relatedView, attribute: .Right, multiplier: 1.0, constant: 5))
        self.myView.addConstraint(NSLayoutConstraint(item: subView, attribute: .FirstBaseline, relatedBy: .Equal, toItem: relatedView, attribute: .LastBaseline, multiplier: 1.0, constant: 0))
    } else {
        self.myView.addConstraint(NSLayoutConstraint(item: subView, attribute: .Top, relatedBy: .Equal, toItem: relatedView, attribute: .Bottom, multiplier: 1.0, constant: 8.0))
        self.myView.addConstraint(NSLayoutConstraint(item: subView, attribute: .Leading, relatedBy: .Equal, toItem: self.headerStackView, attribute: .Leading, multiplier: 1.0, constant: 8.0))
        self.myView.addConstraint(NSLayoutConstraint(item: subView, attribute: .Width, relatedBy: .Equal, toItem: self.myView, attribute: .Width, multiplier: 1.0, constant: -15))
        self.myView.addConstraint(NSLayoutConstraint(item: relatedView, attribute: .Width, relatedBy: .Equal, toItem: self.myView, attribute: .Width, multiplier: 1.0, constant: -15))
        subViews.append(relatedView)
    }

    subViews.append(subView)


    return subViews
}


func setSimilarConstraintsToTitlesLabels(subView:UILabel, relatedView:UIView) {
    subView.translatesAutoresizingMaskIntoConstraints = false
    subView.textColor = UIColor.grayColor()
    subView.numberOfLines = 0
    self.myView.addSubview(subView)
    self.myView.addConstraint(NSLayoutConstraint(item: subView, attribute: .Top, relatedBy: .Equal, toItem: relatedView, attribute: .Bottom, multiplier: 1.0, constant: 8.0))
    self.myView.addConstraint(NSLayoutConstraint(item: subView, attribute: .Leading, relatedBy: .Equal, toItem: self.headerStackView, attribute: .Leading, multiplier: 1.0, constant: 0))
}
}

方法&#34; informationUpdate()&#34;在解析显示信息时调用。

2 个答案:

答案 0 :(得分:0)

我认为您应该尝试创建更清晰的代码。不要使用subviews的“盲”数组;不要将视图直接附加到subviews属性,您已将其添加到视图层次结构中;如果你使用autolayout(translatesAutoresizingMaskIntoConstraints = false) - 不要尝试在单个视图中将它与帧混合,去设置所有约束;为不同的视图使用不同的背景颜色来调试运行时的视图层次结构转到Xcode Debug \ View Debugging \ Capture View Hierarchy ,以便在运行时深入探索视图层次结构

此外,如果numberOfRowsInSectionUITableView调用并返回值&gt; 0(检查它!),然后cellForRowAtIndexPath 必须立即调用此UITableView,因为设置了dataSource属性。如果您有多个UITableView个对象 - 请检查是否没有意外替换。

P.S。如果你来自俄罗斯我可以帮助俄罗斯郎

答案 1 :(得分:0)

您的tableView没有高度约束,因此高度设置为0。 然后没有可见的单元格=&gt; cellForRow从未调用过:)