2015-03-03 5 views
2

Я не могу заставить UILabel автоматически переносить слова без установки явной предпочтительной ширины. Пожалуйста помоги.UITableViewCell вычисляет правильную высоту, но UILabel не переносит

Вот мой Interface Builder для UILabel в UITableViewCell

UILabel IB Attributes Inspector UILabel IB Size Inspector

И мой результат:

Application Example Result

Однако, если явно указать preferredWidth как в:

explicit height

я получаю следующее:

With wordwrapping

Конечно это имеет некоторые странные вертикальные интервалы, но, по крайней мере, это правильно оборачивать.

Кроме того, вот как я строю строку в моем UITableViewController:

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!, object: PFObject!) -> PFTableViewCell! { 

    let cell = tableView.dequeueReusableCellWithIdentifier(Constants.CellReuseIdentifier, forIndexPath: indexPath) as? BurnFeedTableViewCell ?? 
     BurnFeedTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: Constants.CellReuseIdentifier) 

    cell.nameOfBurnLabel?.text = object.objectForKey("name") as? String 
    if let owner = object.objectForKey("owner") as? PFUser { 
     cell.ownerLabel?.text = owner.username 
    } else { 
     cell.ownerLabel?.text = "unknown" 
    } 

    return cell 
} 

и определение RowHeight & estimatedRowHeigh как:

override func viewDidLoad() { 
    super.viewDidLoad() 

    self.tableView.estimatedRowHeight = 100.0 
    self.tableView.rowHeight = UITableViewAutomaticDimension 
} 

Я действительно хотел бы получить эту работу, не имея для указания явной высоты. Кроме того, я не играл с contentCompressionResistancePriority без везения.

Это, безусловно, похож на следующий SO Вопрос: Using iOS 8 flexible table cells, cell height changes but text doesn't wrap

Однако, кажется, не подходит там, как будет работать. На самом деле, есть несколько подобных вопросов. Я не могу заставить их работать.

EDIT: XML в tableViewCell от main.storyboard

<tableViewCell contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" reuseIdentifier="Burn Feed Cell" 
       rowHeight="95" id="bif-hV-Vqt" customClass="BurnFeedTableViewCell" customModule="Burn" 
       customModuleProvider="target"> 
    <rect key="frame" x="0.0" y="0.0" width="600" height="44"/> 
    <autoresizingMask key="autoresizingMask"/> 
    <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" 
           contentMode="center" tableViewCell="bif-hV-Vqt" id="KGP-Sx-cZC"> 
     <autoresizingMask key="autoresizingMask"/> 
     <subviews> 
      <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" 
        verticalHuggingPriority="251" text="owner" lineBreakMode="tailTruncation" 
        baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" 
        translatesAutoresizingMaskIntoConstraints="NO" id="TZ9-cx-K29"> 
       <rect key="frame" x="8" y="37" width="48" height="21"/> 
       <fontDescription key="fontDescription" type="system" pointSize="17"/> 
       <color key="textColor" cocoaTouchSystemColor="darkTextColor"/> 
       <nil key="highlightedColor"/> 
      </label> 
      <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" 
        verticalHuggingPriority="251" text="Burn Name" lineBreakMode="wordWrap" numberOfLines="0" 
        baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" preferredMaxLayoutWidth="90" 
        translatesAutoresizingMaskIntoConstraints="NO" id="v96-dx-9z5"> 
       <rect key="frame" x="8" y="8" width="584" height="21"/> 
       <fontDescription key="fontDescription" type="system" pointSize="17"/> 
       <color key="textColor" cocoaTouchSystemColor="darkTextColor"/> 
       <nil key="highlightedColor"/> 
      </label> 
      <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" 
        verticalHuggingPriority="251" text="countdown" lineBreakMode="tailTruncation" 
        baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" 
        translatesAutoresizingMaskIntoConstraints="NO" id="6YZ-ne-79f"> 
       <rect key="frame" x="506" y="37" width="86" height="21"/> 
       <fontDescription key="fontDescription" type="system" pointSize="17"/> 
       <color key="textColor" cocoaTouchSystemColor="darkTextColor"/> 
       <nil key="highlightedColor"/> 
      </label> 
     </subviews> 
     <constraints> 
      <constraint firstItem="v96-dx-9z5" firstAttribute="leading" secondItem="KGP-Sx-cZC" 
         secondAttribute="leadingMargin" id="Iwe-kT-1Do"/> 
      <constraint firstItem="6YZ-ne-79f" firstAttribute="trailing" secondItem="KGP-Sx-cZC" 
         secondAttribute="trailingMargin" id="JOA-d6-q3X"/> 
      <constraint firstItem="6YZ-ne-79f" firstAttribute="baseline" secondItem="TZ9-cx-K29" 
         secondAttribute="baseline" id="JXU-Hf-vVb"/> 
      <constraint firstItem="TZ9-cx-K29" firstAttribute="leading" secondItem="KGP-Sx-cZC" 
         secondAttribute="leadingMargin" id="VOG-Xh-9wd"/> 
      <constraint firstAttribute="bottomMargin" relation="greaterThanOrEqual" secondItem="TZ9-cx-K29" 
         secondAttribute="bottom" constant="5" id="am1-l0-8EV"/> 
      <constraint firstItem="TZ9-cx-K29" firstAttribute="top" secondItem="v96-dx-9z5" secondAttribute="bottom" 
         constant="8" symbolic="YES" id="jLQ-yQ-A8V"/> 
      <constraint firstItem="v96-dx-9z5" firstAttribute="trailing" secondItem="KGP-Sx-cZC" 
         secondAttribute="trailingMargin" id="sl2-Fb-sWy"/> 
      <constraint firstItem="v96-dx-9z5" firstAttribute="top" secondItem="KGP-Sx-cZC" secondAttribute="topMargin" 
         id="xt3-Em-EaP"/> 
     </constraints> 
    </tableViewCellContentView> 
    <connections> 
     <outlet property="countdownLabel" destination="6YZ-ne-79f" id="te1-QF-Nuo"/> 
     <outlet property="nameOfBurnLabel" destination="v96-dx-9z5" id="Wki-e1-0Np"/> 
     <outlet property="ownerLabel" destination="TZ9-cx-K29" id="wqh-Cj-yQX"/> 
    </connections> 
</tableViewCell> 

ответ

0

Ваш вопрос с autolayout. Чтобы получить правильную упаковку ширины и высоты, вам необходимо убедиться, что для всех элементов вашего UITableViewCell должным образом ограничены левое поле ячейки справа и от верхнего края до нижней.

+0

Я знаю об этом, и все должно быть в состоянии вычислить его х, и вы координируете без двусмысленности. Я не играл с разными измерениями. Если бы я мог поделиться своими ограничениями, вы могли бы сказать мне, что нужно исправлять? –

+0

уверен. опубликуйте все ограничения на элементы ячеек с вашим вопросом – kellanburket

+0

Отредактированный вопрос с XML-тегом subjectviewview из main.storyboard –

0

Вы отключили автоматический перенос маскировки для всех этикеток?

cell.nameOfBurnLabel.setTranslatesAutoresizingMaskIntoConstraints(false) 
cell.ownerLabel.setTranslatesAutoresizingMaskIntoConstraints(false) 
cell.countdownLabel.setTranslatesAutoresizingMaskIntoConstraints(false) 

По крайней мере, это то, что я должен был сделать, чтобы получить динамические высоты ячеек для работы с ярлыками.

+1

Не нужно, так как Cell является частью раскадровки –

Смежные вопросы