iosswiftautolayoutxcode-6.2

Dynamic Pictures Adding in table View


I'm trying to do a bit tricky thing for me (new to the layout constraints thing).

The idea is that I have to dynamically add pictures to a table cell.The cell structure is:

  1. an image view
  2. text view
  3. scroll view (horizontal scrolling) which contain images inside the images part & number isn't always there neither it's constant (Some Cells contains images & texts and the others only text) that's why i need to add the constraints programatically.

I've searched a lot and applied a lot of things but now I'm getting exceptions and the application is crashing. Hope u can help me. Here's my code:

        var imgsScrollView = UIScrollView()
        cell.employmentEventTextView.text = employmentEventsList[indexPath.row].body
        if (imgsCountintheCell == 1){
            eventsListView.rowHeight = 220
        }else{
            eventsListView.rowHeight = 500
        }
        for var i = 0 ; i < imgsCountintheCell ; i++ {

            if(i == 0){

                var int : String = String(i)
                //getting the image from URL Block
                var imgName = "image" + int
                let url = NSURL(string: employmentEventsList[indexPath.row].imgs[i])
                let data = NSData(contentsOfURL: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check
                let image = UIImage(data: data!)
                let imgView = UIImageView(image: image!)
                imgView.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
                imgView.setTranslatesAutoresizingMaskIntoConstraints(false)

                var constX = NSLayoutConstraint(item: imgView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
                var constTop = NSLayoutConstraint(item: imgView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: cell.employmentEventTextView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 2)

                var textPlaceBottom = NSLayoutConstraint(item: cell.employmentEventTextView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: imgView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 2)
                eventsListView.addSubview(imgView)
                imgView.addConstraint(constX)
                imgView.addConstraint(constTop)
                cell.employmentEventTextView.addConstraint(textPlaceBottom)

            }else{
                var int : String = String(i)
                //getting the image from URL Block
                var imgName = "image" + int
                let url = NSURL(string: employmentEventsList[indexPath.row].imgs[i])
                let data = NSData(contentsOfURL: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check
                let image = UIImage(data: data!)
                let imgView = UIImageView(image: image!)
                imgView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
                imgView.setTranslatesAutoresizingMaskIntoConstraints(false)
                let constscrollViewToTheTop = NSLayoutConstraint(item: imgsScrollView, attribute: NSLayoutAttribute.Top, relatedBy: .Equal, toItem: cell.employmentEventTextView , attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 5)

                imgsScrollView.addSubview(imgView)
                eventsListView.addSubview(imgsScrollView)
                imgsScrollView.addConstraint(constscrollViewToTheTop)

            }

and my exception code is:

Assertion failure in -[UIImageView nsli_lowerAttribute:intoExpression:withCoefficient:forConstraint:], /SourceCache/UIKit_Sim/UIKit-3318.93/NSLayoutConstraint_UIKitAdditions.m:3502
2015-05-27 01:49:58.097 طاقات علم[1713:38226] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Unexpected use of internal layout attribute'
*** First throw call stack:
(
0   CoreFoundation                      0x0000000100cc1a75 __exceptionPreprocess + 165
1   libobjc.A.dylib                     0x0000000102819bb7 objc_exception_throw + 45
2   CoreFoundation                      0x0000000100cc18da +[NSException raise:format:arguments:] + 106
3   Foundation                          0x000000010115cb6f -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 195
4   UIKit                               0x0000000101bdea77 -[UIView(AdditionalLayoutSupport) nsli_lowerAttribute:intoExpression:withCoefficient:forConstraint:] + 3483
5   Foundation                          0x00000001010e2b9e lower_1_attribute + 158
6   Foundation                          0x00000001010e26b4 -[NSLayoutConstraint _lowerIntoExpression:reportingConstantIsRounded:] + 102
7   Foundation                          0x00000001010d862e -[NSLayoutConstraint _addToEngine:integralizationAdjustment:mutuallyExclusiveConstraints:] + 96
8   UIKit                               0x0000000101bd0cf9 -[UIView(UIConstraintBasedLayout) _layoutEngine_didAddLayoutConstraint:roundingAdjustment:mutuallyExclusiveConstraints:] + 411
9   UIKit                               0x0000000101bd0f94 -[UIView(UIConstraintBasedLayout) _tryToAddConstraintWithoutUpdatingConstraintsArray:roundingAdjustment:mutuallyExclusiveConstraints:] + 30
10  UIKit                               0x0000000101bd10bc -[UIView(UIConstraintBasedLayout) _tryToAddConstraint:roundingAdjustment:mutuallyExclusiveConstraints:] + 243
11  طاقات علم                   0x0000000100910764 _TFCX15__ymcamGdqDduaj30EmploymentEventsViewController9tableViewfS0_FTCSo11UITableView21cellForRowAtIndexPathCSo11NSIndexPath_CSo15UITableViewCell + 7892
12  طاقات علم                   0x000000010091164f _TToFCX15__ymcamGdqDduaj30EmploymentEventsViewController9tableViewfS0_FTCSo11UITableView21cellForRowAtIndexPathCSo11NSIndexPath_CSo15UITableViewCell + 79
13  UIKit                               0x000000010164be03 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 508
14  UIKit                               0x000000010162b901 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2846
15  UIKit                               0x000000010164178c -[UITableView layoutSubviews] + 213
16  UIKit                               0x00000001015ce1c3 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 521
17  QuartzCore                          0x00000001054d6c58 -[CALayer layoutSublayers] + 150
18  QuartzCore                          0x00000001054cb87e _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
19  QuartzCore                          0x00000001054cb6ee _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
20  QuartzCore                          0x000000010543936e _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
21  QuartzCore                          0x000000010543a482 _ZN2CA11Transaction6commitEv + 390
22  QuartzCore                          0x000000010543aaed _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 89
23  CoreFoundation                      0x0000000100bf6507 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
24  CoreFoundation                      0x0000000100bf6460 __CFRunLoopDoObservers + 368
25  CoreFoundation                      0x0000000100bec293 __CFRunLoopRun + 1123
26  CoreFoundation                      0x0000000100bebbc6 CFRunLoopRunSpecific + 470
27  GraphicsServices                    0x0000000104dcaa58 GSEventRunModal + 161
28  UIKit                               0x0000000101554580 UIApplicationMain + 1282
29  طاقات علم                   0x000000010094c19e top_level_code + 78
30  طاقات علم                   0x000000010094c27a main + 42
31  libdyld.dylib                       0x0000000102ff5145 start + 1
32  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

thx in advance for any help


Update: I noticed a way to work around my problem and it seems to work, the idea is that I can use the concept of constraints of blank objects just gets disabled automatically (when an image view is empty the text view automatically moves upward) and I found it just okay for me.Easy & fast solution . Now I have a question to ask: is there a way to make the same table have multiple values for the row hight ? ( for example the first and second row have row.hight = 60 because they have no picture and the third row has row.hight = 500 because it have pictures.)

Is it possible to give each cell a separate hight value in the same table ?


Solution

  • Personally I find it easier to create a nib file for cells, then 'collapse' constraints if certain views should be hidden. Eg create a nib with your UIImageView, UITextView and UIScrollView and all constraints. Add IBOutlets for the views and for the view's height/width constraints. Then if you need to hide a view, set its height/width constraint constant to 0.

    Note as you should be recycling your cells you'll need to reset the constraint constants in -(void)prepareForReuse

    You can set a different height for each cell by implementing the UITableView delegate method (in Swift the syntax will be different, but the name the same)

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    

    For each row you can return a different height.

    It can get a bit tricky with complex heights because sometimes you have to build you cell to calculate its height, then you have to build it again in cellForRowAtIndexPath