引言
在開發中,遇到了一個問題“需要創建或刪除一個按鈕,進行重新排序”,針對該需求的解決辦法就是使用 masonry 進行更新或重新設置約束。此時需要把“數組中元素” 與“添加或刪除的按鈕”相對應,添加或刪除按鈕後,數組也添加或刪除指定元素。在這個地方卡了很久這裏就講述一下該問題的解決思路。
存在問題
樣式交替過程中:進行添加或刪除按鈕,無法讓 button 與數組中元素對應。
如:數組中有元素[ @ “第一條消息”, @ “第二條消息” , @ “第三條消息” , @ “第四條消息”];
此時,刪除,點擊按鈕三進行刪除,按鈕無法與數組中 @ “第三條消息”元素關聯。
解決思路
思路1.點擊刪除按鈕後,使用“ button.title ” 與 “數組中元素”相關聯,但是發現:如果數組中有同名相,會刪除所有該名稱的按鈕,所以該思路不可取。
//如:數組中元素爲[ @ "第一條消息", @ "第二條消息", @ "第二條消息", @ "第三條消息"];
- (void)removeButtonClick:(UIButton *)button {
//此時 button.title 爲 @"第二條消息"
[self.adressArray removeObject:button.title];
[button removeFromSuperview];
//此時 數組元素與按鈕不能對應,多刪除了一個元素
//數組元素爲[@"第一條消息", @"第三條消息"];
}
思路2.給每個 button 添加一個 tag,每次進行:添加或刪除 button 後,對所有 button 重新設置 tag,保證每次 tag 都能與數組元素相對應。
最後採取思路2進行設置。
解決辦法
第一步:設置創建按鈕。
- 創建按鈕,設置標題,添加點擊事件,添加按鈕。
- 刷新 buttonsView。
//數組中添加元素
[self.buttonsArray addObject:"第五條消息"];
//創建一個Butoton,通過 tag 與數組元素關聯
UIButton *addButton = [[UIButton alloc] init];
[addButton setTitle:"第五條消息" forState:UIControlStateNormal];
[addButton addTarget:self action:@selector(removeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
[self.buttonsView addSubview:addButton];
//刷新 buttonsView
[self reloadButtonsView];
第二步:設置點擊刪除按鈕。
- 刪除按鈕時:數組移除 移除指定項:self.buttonsArray removeObjectAtIndex:button.tag - 101。
- button removeFromSuperview 將此按鈕從父控件中移除。
- 刷新 buttonsView。
//設置刪除點擊事件
- (void)removeButtonClick:(UIButton *)button {
//根據 button 的 tag 值,找到數組中指定元素所在位置,移除該元素
[self.buttonsArray removeObjectAtIndex:button.tag - 101];
//將此按鈕從父控件中移除
[button removeFromSuperview];
//刷新 buttonsView
[self reloadButtonViews];
}
第三步:設置刷新 buttonsView 的方法
- for 循環遍歷 buttonsView 的所有 button。
- 對裏面的所有 button 重新設置 button 的 tag 值,給按鈕添加一個 tag,tag 值爲 self.buttonsArray.count + 100 (+100是防止 butonsView 中子控件的 tag 重名)。
- 對裏面的所有button使用 mas_remakeConstraints 重新設置約束。
//設置刷新 buttonsView 方法
- (void)reloadButtonViews {
//設置 button 相對 buttonsView 的頂部距離 ,起始值爲0
CGFloat addButtonTopMargin = 0;
//遍歷 buttonsView 中所有 button
for (int i = 0; i < self.buttonsView.subviews.count; i++) {
//計算第 i 個 button 的高度,
addButtonTopMargin = i * (buttonHeight + buttonMargin);
///取出 buttonsView 中第 i 個 button
UIButton * button = self.buttonsView.subviews[i];
//將 button 與數組中元素相關聯,以便根據每個 button 找到數組中指定元素 (+100是防止 butonsView 中子控件的 tag 重名)。
button.tag = self.buttonsArray.count + 100;
//把 buttonsView 中所有 button 使用 mas_remakeConstraints 重新設置高度
[button mas_remakeConstraints:^(MASConstraintMaker *make) {
make.top.mas_equalTo(self.buttonsView).offset(deleteButtonTopMargin);
make.left.mas_equalTo(self.buttonsView);
make.height.mas_equalTo(CC_GETHEIGH(13));
}];
};
//最後使用 mas_updateConstraints 更新 buttonsView 的高度
[self.buttonsView mas_updateConstraints:^(MASConstraintMaker *make) {
make.height.mas_equalTo(addButtonTopMargin + CC_GETOFFSET(13 +20));
}
}];
}
總結歸納
1.讓 buttonsView 與 button 位置動態變化的方式就是使用 masonry 更新或重寫約束。
2.讓 “button” 與“數組元素” 相關聯的方式就是使用 button.tag,並且在每次添加或刪除後,重新設置所有
button.tag,讓任何時候 button.tag 都與數組中元素參數對應關係。