动态地将视图插入到具有动态高度

时间:2016-03-04 17:26:46

标签: ios swift2 custom-cell uitableview

Hello Guys我花了几天时间弄清楚如何解决我的问题,而且我对swift的熟练程度不高,我决定问一些专业人士

我的问题:

DATA:事件的数组列表(apointment,task等...) 事件的数量并不总是相同的,这就是为什么我必须插入尽可能多的视图作为数组中的事件和每个单元格的高度总是不同的

使用xib文件创建的自定义单元格

enter image description here

我在单元格中插入视图(创建点和任务列)但滚动时一切都开始看起来非常糟糕。有人可以帮助我,并在滚动时告诉我为什么它看起来像破碎的乐高?

我想制作类似enter image description here

的内容

我尝试在我的视图列的左侧添加标签,但它不起作用。单元格高度很小,内容没有出现,因为隐藏在下一行。细胞高度只是那一个标签的高度。它忽略了最后一个视图的约束,只注意到该标签的约束

的ViewController

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var data = [PLCalendarDay]()

var tableView : UITableView!

let days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]


override func viewDidLoad() {
    super.viewDidLoad()
    for (var i = 0; i<5; i++) {
        var boleen = true
        if i > 2 {boleen = false}
        let calendar = NSCalendar.currentCalendar()
        let day = calendar.dateByAddingUnit(.Day, value: i, toDate: NSDate(), options: [])
        print("robim pole")
        self.data.append(PLCalendarDay(day: day!, withEnd: boleen))
    }
    tableView = UITableView()
    tableView.registerNib(UINib(nibName: "PLCalendarCell", bundle: nil), forCellReuseIdentifier: "PLCalendarCellid")
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 200
    tableView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
    tableView.delegate = self
    tableView.dataSource = self
    tableView.separatorStyle = .None
    self.view.addSubview(tableView!)

    // Do any additional setup after loading the view, typically from a nib.
}

override func viewDidAppear(animated: Bool) {
    //        self.tableView.reloadSections(NSIndexSet(indexesInRange: NSMakeRange(0, self.tableView.numberOfSections)), withRowAnimation: .None)
}



override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    print("davam cell number")
    return data.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    print("davam cell")
    let cell = tableView.dequeueReusableCellWithIdentifier("PLCalendarCellid", forIndexPath: indexPath) as! PLCalendarCell
    cell.setupCell(data[indexPath.row].events)
    //cell.selectionStyle = .None
   //      cell.day.text = data[indexPath.row].date.dateStringWithFormat("dd")
  //        let day = data[indexPath.row].date.dateStringWithFormat("dd-MM-yyyy")
   //        cell.dayWord.text = days[getDayOfWeek(day)!-1]
    print("som awake1 1 1 ")
    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    // cell selected code here
}

func getDayOfWeek(today:String)->Int? {

    let formatter  = NSDateFormatter()
    formatter.dateFormat = "dd-MM-yyyy"
    if let todayDate = formatter.dateFromString(today) {
        let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
        let myComponents = myCalendar.components(.Weekday, fromDate: todayDate)
        let weekDay = myComponents.weekday
        return weekDay
    } else {
        return nil
    }
}

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

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 200
}

}

单元格文件

class PLCalendarCell: UITableViewCell {



@IBOutlet weak var day: UILabel!
@IBOutlet weak var dayWord: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
    print("som awake")
    // Initialization code
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

func setupCell (events: [PLCalendarEvent]){
    let cellWidht = self.contentView.frame.width
    var positionY:CGFloat = 10.0
    var lastView: UIView? = nil

    for event in events {

        if event.end != nil {

            let view = PLCalendarCellView(frame: CGRectMake(70, positionY, cellWidht, 50.0), time: true)
            view.title.text = event.desc
            view.time.text = "\(event.start.dateStringWithFormat("dd-MM-yyyy")) - \(event.end!.dateStringWithFormat("dd-MM-yyyy"))"
            view.backgroundColor = UIColor.greenColor()
            view.layer.cornerRadius = 4
            self.addSubview(view)
            if lastView == nil {
                let constrain =  NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.TopMargin, multiplier: 1, constant: 10)
                self.addConstraint(constrain)
            } else {
                let constrain =  NSLayoutConstraint(item: lastView!, attribute: NSLayoutAttribute.BottomMargin, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 10)
                self.addConstraint(constrain)
            }
            lastView = view
            positionY += 60.0

        }
        else {

            let view = PLCalendarCellView(frame: CGRectMake(70, positionY, cellWidht, 30.0), time: false)
            view.title.text = event.desc
            view.backgroundColor = UIColor.greenColor()
            view.layer.cornerRadius = 4
            self.addSubview(view)
            if lastView == nil {
                let constrain =  NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.TopMargin, multiplier: 1, constant: 10)
                self.addConstraint(constrain)
            } else {
                let constrain =  NSLayoutConstraint(item: lastView!, attribute: NSLayoutAttribute.BottomMargin, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 10)
                self.addConstraint(constrain)
            }
            lastView = view
            positionY += 40.0

        }
    }

   //        eventHolderView.frame = CGRectMake(0, 0, cellWidht, positionY)

    //        let constrain =  NSLayoutConstraint(item: self.contentView, attribute: NSLayoutAttribute.BottomMargin, relatedBy: NSLayoutRelation.Equal, toItem: lastView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 10)
  //        self.addConstraint(constrain)
    let constrain =  NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.BottomMargin, relatedBy: NSLayoutRelation.Equal, toItem: lastView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 10)
    self.addConstraint(constrain)

}

}

Callendar日

class PLCalendarDay: NSObject {
let date: NSDate!
var events = [PLCalendarEvent]()

init(day: NSDate, withEnd: Bool) {

    self.date = NSCalendar.currentCalendar().startOfDayForDate(day)

    if withEnd {

        for(var i=0; i<5;i++){
            events.append(PLCalendarEvent(description: "Only one day", startDate: NSCalendar.currentCalendar().startOfDayForDate(date)))
        }

    } else {

        for(var i=0; i<5;i++){
            events.append(PLCalendarEvent(description: "Only one day", startDate: NSCalendar.currentCalendar().startOfDayForDate(date), endDate: date))
        }

    }

}

}

Callendar活动

class PLCalendarEvent : NSObject{

let desc: String
let start: NSDate
var end: NSDate? = nil

init(description: String, startDate: NSDate) {
    self.desc = description
    self.start = startDate
}

init(description: String, startDate: NSDate, endDate: NSDate) {
    self.desc = description
    self.start = startDate
    self.end = endDate
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

}

我真的无法取得任何好成绩,我会非常感谢你的帮助

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。我所需要的只是适当的约束,但不仅是垂直的,甚至是水平的。