3 回答

TA貢獻1812條經驗 獲得超5個贊
一種更好,更干凈的方法是將UITableViewCell子類化并覆蓋其-setFrame:方法,如下所示:
- (void)setFrame:(CGRect)frame {
frame.origin.x += inset;
frame.size.width -= 2 * inset;
[super setFrame:frame];
}
為什么會更好?因為其他兩個更糟。
在中調整表格視圖寬度 -viewWillAppear:
首先,這是不可靠的,在-viewWillAppear:調用后,超級視圖或父視圖控制器可能會進一步調整表視圖框架。當然,您可以-setFrame:為UITableView 子類化和重寫,就像我在這里為UITableViewCells所做的一樣。但是,對UITableViewCells進行子類化是一種非常普遍,輕便和Apple的方式。
其次,如果您的UITableView具有backgroundView,則不希望將backgroundView一起縮小。在縮小UITableView寬度的同時保持backgroundView寬度并不是一件容易的事,更不用說首先將子視圖擴展到其Superview之外并不是一件很優雅的事情。
自定義單元格渲染以偽造更窄的寬度
為此,您必須準備帶有水平邊距的特殊背景圖像,并且必須自己布置單元格的子視圖以容納邊距。相比之下,如果您只是調整整個單元格的寬度,則自動調整大小將為您完成所有工作。

TA貢獻1799條經驗 獲得超8個贊
要在不提供設置變量方法的Swift中進行此操作,您必須覆蓋的setter frame。原帖(至少在我找到它)在這里
override var frame: CGRect {
get {
return super.frame
}
set (newFrame) {
let inset: CGFloat = 15
var frame = newFrame
frame.origin.x += inset
frame.size.width -= 2 * inset
super.frame = frame
}
}

TA貢獻1815條經驗 獲得超13個贊
我發現接受的解決方案在旋轉時不起作用。為了實現具有固定寬度和靈活邊距的UITableViewCells,我將上述解決方案調整為以下內容:
- (void)setFrame:(CGRect)frame {
if (self.superview) {
float cellWidth = 500.0;
frame.origin.x = (self.superview.frame.size.width - cellWidth) / 2;
frame.size.width = cellWidth;
}
[super setFrame:frame];
}
每當設備旋轉時都會調用該方法,因此單元將始終居中。
- 3 回答
- 0 關注
- 614 瀏覽
添加回答
舉報