Как отразить свойства UILabel другому?
Я пытаюсь настроить UITableViewController
динамически. Поэтому я изменил многие свойства cell.textLabel
. Теперь я хочу скопировать эти свойства на detailTextLabel
и на одну метку, созданную с помощью кода. Как это можно сделать?
cell.textLabel.backgroundColor = [UIColor colorWithRed:0 green:0.188235 blue:0.313725 alpha:1];
cell.textLabel.textColor=[UIColor whiteColor];
cell.textLabel.font=[UIFont fontWithName:@"HelveticaNeue" size:26];
cell.textLabel.autoresizingMask=UIViewAutoresizingFlexibleRightMargin;
Это мой cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
cell.textLabel.text=[_names objectAtIndex:indexPath.row];
cell.textLabel.tag=indexPath.row;
cell.detailTextLabel.text=[_phones objectAtIndex:indexPath.row];
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow.png"] ];
[imageView setFrame:CGRectMake(380,10,30,50)];
[cell addSubview:imageView];
//customize the seperator
UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1000, 1)];/// change size as you need.
separatorLineView.backgroundColor = [UIColor grayColor];// you can also put image here
[cell.contentView addSubview:separatorLineView];
cell.contentView.backgroundColor = [UIColor colorWithRed:0 green:0.188235 blue:0.313725 alpha:1];
cell.textLabel.backgroundColor = [UIColor colorWithRed:0 green:0.188235 blue:0.313725 alpha:1];
cell.textLabel.textColor=[UIColor whiteColor];
cell.textLabel.font=[UIFont fontWithName:@"HelveticaNeue" size:26];
cell.textLabel.autoresizingMask=UIViewAutoresizingFlexibleRightMargin;
//here i want to copy the properties
return cell;
}
Ответы
Ответ 1
Для Swift3
class MyLabel: UILabel {
override func draw(_ rect: CGRect) {
super.draw(rect)
backgroundColor = UIColor(red: 0, green: 0.188235, blue: 0.313725, alpha: 1)
textColor = UIColor.white
font = UIFont(name: "HelveticaNeue", size: 26)
autoresizingMask = .flexibleRightMargin
}
}
Создайте подкласс UILabel
таким образом.
#import "MyLabel.h"
@implementation MyLabel
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
self.backgroundColor = [UIColor colorWithRed:0 green:0.188235 blue:0.313725 alpha:1];
self.textColor=[UIColor whiteColor];
self.font=[UIFont fontWithName:@"HelveticaNeue" size:26];
self.autoresizingMask=UIViewAutoresizingFlexibleRightMargin;
}
@end
И теперь создайте объект этого MyLabel, и ваши свойства будут установлены автоматически, а также просто назначат этот класс вашей метке через раскадровку на ярлык в вашей ячейке.
Подкласс - лучший способ для реализации кода многократного использования.
Или вы даже можете создать расширение класса или даже метод класса в каком-то классе, который принимает UILabel
и устанавливает свойства, но все это не лучшие методы. Другая проблема с расширениями заключается в том, что вы можете использовать только self
, но не super
. Это может создать проблемы в будущем, когда вам нужно расширить свойства.
Надеюсь, я понятен и полезен.
Ответ 2
Вы можете использовать этот метод, чтобы сделать все метки UITabelViewCell
одинаковым свойством
Здесь просто продирайте subViews и проверьте, имеет ли subview значение UILabel
, если оно имеет значение UILabel
, затем установите требуемое свойство.
Мой код:
- (void)formatTheLabelForCell:(UITableViewCell *)cell
{
for (UIView *view in cell.contentView.subviews) {
if ([view isKindOfClass:[UILabel class]]) {
UILabel *lbl = (UILabel *)view;
lbl.backgroundColor = [UIColor colorWithRed:0 green:0.188235 blue:0.313725 alpha:1];
lbl.textColor=[UIColor whiteColor];
lbl.font=[UIFont fontWithName:@"HelveticaNeue" size:26];
lbl.autoresizingMask=UIViewAutoresizingFlexibleRightMargin;
}
}
}
Ответ 3
Вместо настройки ячейки в cellForRowAtIndexPath
, лучше использовать пользовательскую ячейку. Добавьте imageView
и separatorLineView
в свою раскадровку/нить. Таким образом, все ячейки генерируются с помощью этих свойств по умолчанию. Также, если вам нужно что-то сконфигурировать с помощью кода, вы можете закодировать его в своем файле CustomCell.m следующим образом:
class CustomCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
self.textLabel.backgroundColor = UIColor.redColor
//do other configurations
}
Изменить: загрузка изображений из Интернета может быть причиной длительного хранения ячеек. Попробуйте загружать изображения асинхронно. Вы также можете использовать эту библиотеку: SDWebImage
Примечание. Я знаю, что вы хотите этого в Objective C, код выше в Swift показан только для иллюстрации.
Ответ 4
Что касается swift, вы можете сделать это, он скопирует все атрибуты, которые вы применили к textLabel, к detailTextLabel.
cell.detailTextLabel.attributedText = cell.textLabel.attributedText
Ответ 5
Прежде всего, я не думаю, что есть функция для копирования определенных свойств любого компонента UIKit в SDK для iOS. Поэтому для этого вам придется написать настраиваемую функцию. Кроме того, есть некоторые проблемы с вашей "cellForRowAtIndexPath", как указано другими в комментариях.
Существуют разные решения.
Решение 1:
Напишите функцию в контроллере вида, которая берет две метки в качестве параметров и копирует нужные значения.
-(void)copyPropertiesFrom:(UILabel*)label1 toLabel:(UILabel*)label2{
label2.backgroundColor = label1.backgroundColor;
label2.textColor = label1.textColor;
label2.font = label1.font;
label2.autoresizingMask = label1.autoresizingMask;
}
В cellForRowAtIndexPath, где вы хотите скопировать, сделайте это
[self copyPropertiesFrom:cell.titleLabel toLabel:cell.detailTextLabel];
Решение 2 (рекомендуется): Это лучше всего в моем маленьком опыте, потому что вы можете повторно использовать его в других контроллерах представлений. Там может быть лучший подход, чем это.
Создайте категорию UILabel. Проверьте эту ссылку Как создать категорию в Xcode 6 или выше?, а также этот https://code.tutsplus.com/tutorials/objective-c-categories--mobile-10648
Ваша функция внутри категории будет выглядеть следующим образом.
-(void)formatLabelToMyStyle{
self.backgroundColor = [UIColor colorWithRed:0 green:0.188235 blue:0.313725 alpha:1];
self.textColor = [UIColor whiteColor];
self.font = [UIFont fontWithName:@"HelveticaNeue" size:26];
self.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
}
Вы включите заголовочный файл категории и вызовите эту функцию в свой cellForRowAtIndexPath, как это
[cell.titleLabel formatLabelToMyStyle];
[cell.detailTextLabel formatLabelToMyStyle];
[cell.customTextLabel formatLabelToMyStyle];
И что касается вашего cellForRowAtIndexPath, larme упоминается в комментариях "Не добавляйте subview, как это в ячейках, потому что ячейки повторно используются". Это будет продолжать добавлять представления к вашей ячейке, тем самым вызывая проблемы с памятью. Особенно если у вас есть большое количество ячеек, в вашем случае это правда.
Ответ 6
Вы можете использовать Category
для UILabel
или использовать подкласс UILabel
, который должен использовать один и тот же стиль.
A Category
для UILabel
может выглядеть так:
// UILabel+CustomStyle.h
#import <UIKit/UIKit.h>
@interface UILabel (CustomStyle)
-(void) applyCustomStyle;
@end
.m file:
// UILabel+CustomStyle.m
#import "UILabel+CustomStyle.h"
@implementation UILabel (CustomStyle)
-(void) applyCustomStyle {
self.backgroundColor = [UIColor colorWithRed: 0 green: 0.188235 blue: 0.313725 alpha: 1];
self.textColor = [UIColor whiteColor];
self.font = [UIFont fontWithName: @"HelveticaNeue" size: 26];
self.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
}
@end
Затем вы можете применить один и тот же стиль, просто позвонив:
#import "UILabel+CustomStyle.h"
[label applyCustomStyle];
Ответ 7
Если вы хотите использовать такую же конфигурацию ярлыков во многих местах проекта. Просто подкласс, как сказал @NikhilManapure.
ИЛИ
Если вы хотите применить те же свойства к TableViewCell textLabel и detailTextLabel. Вы должны подклассифицировать TableViewCell и переопределить свойства метки в методе drawrect.
Objective-C
#import <UIKit/UIKit.h>
@interface PropertiesCell : UITableViewCell
@end
#import "PropertiesCell.h"
@implementation PropertiesCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
[self cellLabelConfigure:self.textLabel];
[self cellLabelConfigure:self.detailTextLabel];
}
- (void)cellLabelConfigure:(UILabel*) contentLabel {
contentLabel.backgroundColor = [UIColor colorWithRed:0 green:0.188235 blue:0.313725 alpha:1];
contentLabel.textColor=[UIColor whiteColor];
contentLabel.font=[UIFont fontWithName:@"HelveticaNeue" size:26];
contentLabel.autoresizingMask=UIViewAutoresizingFlexibleRightMargin;
}
@end
Свифта
class PropertiesCell: UITableViewCell {
override func draw(_ rect: CGRect) {
super.draw(rect)
cellLabelsConfigure(contentLabel: self.textLabel)
cellLabelsConfigure(contentLabel: self.detailTextLabel)
}
func cellLabelsConfigure(contentLabel: UILabel?) {
contentLabel?.backgroundColor = UIColor(red: 0.0, green: 0.188, blue: 0.313, alpha: 1.0)
contentLabel?.textColor = UIColor.white
contentLabel?.font = UIFont(name: "HelveticaNeue", size: 26.0)
contentLabel?.autoresizingMask = UIViewAutoresizing.flexibleRightMargin
}
}
В раскадровке измените имя класса ячейки на СвойстваCell
![введите описание изображения здесь]()
Ответ 8
Создайте класс расширения и используйте этот метод copy
для передачи всех свойств, которые вы хотите добавить к новой метке.
@implementation UILabel (Copy)
- (UILabel *)copyProperties {
UILabel *label = [UILabel new];
[self copyPropertiesWithLabel:label];
return label;
}
- (void)copyPropertiesWithLabel:(UILabel *)label {
label.backgroundColor = self.backgroundColor;
label.textColor = self.textColor;
label.font = self.font;
label.autoresizingMask = self.autoresizingMask;
// Add more properties
}
@end
Использование:
// cell.textLabel has now all the properties
[theLabelToBeCopied copyPropertiesWithLabel:cell.textLabel];
Ответ 9
Версия Swift3:
extension UILabel {
func copyProperties() -> UILabel {
var label = UILabel()
self.copyProperties(with: label)
return label
}
func copyProperties(with label: UILabel) {
label.backgroundColor = self.backgroundColor
label.textColor = self.textColor
label.font = self.font
label.autoresizingMask = self.autoresizingMask
// Add more properties
}
}
Использование:
theLabelToBeCopied.copyProperties(with: cell.textLabel)
Ответ 10
вы можете сделать это для swift.it будет скопировать для всех атрибутов (textLabel to detailTextLabel). я думаю, что @Nikhil Manapure дал точный ответ.
cell.detailTextLabel.attributedText = cell.textLabel.attributedText