Xamarin.iOS中CollectionViewCell无法显示数据,求代码排查
问题排查:UICollectionViewCell数据赋值后不显示内容
项目内其他CollectionView均正常工作,但当前这个CollectionView的Cell始终无法显示数据。能看到Cell边框、尺寸符合预期,调试时确认数据已赋值给Label,Cell数量与数据源字符串列表数量一致,就是看不到文本内容。
PhoneNumberCell代码
public partial class PhoneNumberCell : UICollectionViewCell { public static readonly NSString Key = new NSString("PhoneNumberCell"); UILabel lblPhoneNumberInfo = new UILabel(); [Export("initWithFrame:")] public PhoneNumberCell(CGRect frame) : base(frame) { // 之前遇到过数据不显示的情况,所以设置了frame和文字颜色,但这里没用,删掉也还是看不到文本 lblPhoneNumberInfo.Frame = new CGRect(0,0,ContentView.Frame.Width, 26f); lblPhoneNumberInfo.TextColor = UIColor.Black; // 能看到Cell的边框 ContentView.Layer.BorderColor = UIColor.LightGray.CGColor; ContentView.Layer.BorderWidth = 2.0f; ContentView.BackgroundColor = UIColor.White; ContentView.Transform = CGAffineTransform.MakeScale(0.8f, 0.8f); } public void SetData(string pPhoneNumberInfo) { lblPhoneNumberInfo.Text = pPhoneNumberInfo; } protected PhoneNumberCell(IntPtr handle) : base(handle) { // 注意:这个构造方法不能包含初始化逻辑 } }
XIB文件内容
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="6211" systemVersion="14A298i" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES"> <dependencies> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7026.1" /> </dependencies> <objects> <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" /> <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder" /> <collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" customClass="PhoneNumberCell" id="cZE-iV-UFb"> <rect key="frame" x="0.0" y="0.0" width="50" height="50" /> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES" /> <view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center"> <rect key="frame" x="0.0" y="0.0" width="50" height="50" /> <autoresizingMask key="autoresizingMask" /> <color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite" /> </view> </collectionViewCell> </objects> </document>
数据源代码(PhoneNumberSource)
public class PhoneNumberSource : UICollectionViewSource { public IList<string> PhoneNumbers; public override nint NumberOfSections(UICollectionView collectionView) { return 1; } public override nint GetItemsCount(UICollectionView collectionView, nint section) { return PhoneNumbers.Count; } public PhoneNumberSource(IList<string> pPhoneNumbers) { PhoneNumbers = pPhoneNumbers; } public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath) { var phoneNumberCell = (PhoneNumberCell)collectionView.DequeueReusableCell(PhoneNumberCell.Key, indexPath); string phoneinfo = PhoneNumbers[indexPath.Row]; phoneNumberCell.SetData(phoneinfo); return phoneNumberCell; } }
CollectionView布局代码
PhoneNumberList.CollectionViewLayout = new UICollectionViewFlowLayout() { ItemSize = new CGSize((float)UIScreen.MainScreen.Bounds.Size.Width, 26f), HeaderReferenceSize = new CGSize(25, 25), SectionInset = new UIEdgeInsets(0, 0, 0, 0), ScrollDirection = UICollectionViewScrollDirection.Vertical, MinimumInteritemSpacing = 0, // 单元格间最小间距 MinimumLineSpacing = 0, };
问题根源与解决方法
核心问题
你创建的lblPhoneNumberInfo标签没有添加到Cell的ContentView上,所以即使赋值了文本,也不会在界面上显示。
修复步骤
在PhoneNumberCell的initWithFrame:构造方法里,添加一行代码将Label添加到ContentView:
ContentView.AddSubview(lblPhoneNumberInfo);
修改后的构造方法:
[Export("initWithFrame:")] public PhoneNumberCell(CGRect frame) : base(frame) { lblPhoneNumberInfo.Frame = new CGRect(0,0,ContentView.Frame.Width, 26f); lblPhoneNumberInfo.TextColor = UIColor.Black; // 添加这行代码 ContentView.AddSubview(lblPhoneNumberInfo); ContentView.Layer.BorderColor = UIColor.LightGray.CGColor; ContentView.Layer.BorderWidth = 2.0f; ContentView.BackgroundColor = UIColor.White; ContentView.Transform = CGAffineTransform.MakeScale(0.8f, 0.8f); }
补充优化建议
- Cell注册方式统一:你同时使用了XIB和代码创建Cell,需确保注册方式正确。如果用XIB,在CollectionView初始化时调用
RegisterNibForCell;如果纯代码创建,调用RegisterClassForCell,两种方式不要混用,避免初始化逻辑不执行。 - 改用AutoLayout适配:
ContentView.Frame.Width在initWithFrame:里可能未正确计算,建议用AutoLayout约束设置Label布局,适配不同尺寸:
lblPhoneNumberInfo.TranslatesAutoresizingMaskIntoConstraints = false; ContentView.AddSubview(lblPhoneNumberInfo); NSLayoutConstraint.ActivateConstraints(new[] { lblPhoneNumberInfo.LeadingAnchor.ConstraintEqualTo(ContentView.LeadingAnchor), lblPhoneNumberInfo.TrailingAnchor.ConstraintEqualTo(ContentView.TrailingAnchor), lblPhoneNumberInfo.TopAnchor.ConstraintEqualTo(ContentView.TopAnchor), lblPhoneNumberInfo.HeightAnchor.ConstraintEqualTo(26) });
内容的提问来源于stack exchange,提问作者Prescott Chartier
相关产品推荐
相关产品推荐

