Como programaticamente adicionar texto a um a uiview
-
13-09-2020 - |
Pergunta
Eu tenho um UIView
que eu gostaria de adicionar vários pedaços de texto.Eu tenho usado um UITextView
mas eu acho que é um exagero que não precisa ser editável.Pensei em utilizar um UILabel
ou um UITextField
, mas eu não vejo como você dizer o superview onde posicionar o UILabel
ou UITextField
dentro de si.Eu quero o menor impacto de objeto que vai me deixar colocar o texto de uma fonte/cor/tamanho da minha escolha na minha UIView
onde eu quero.Não é pedir demais, né?
Solução
A abordagem mais simples para você seria:
UILabel *yourLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 20)];
[yourLabel setTextColor:[UIColor blackColor]];
[yourLabel setBackgroundColor:[UIColor clearColor]];
[yourLabel setFont:[UIFont fontWithName: @"Trebuchet MS" size: 14.0f]];
[yourSuperView addSubview:yourLabel];
De construção, ou seja, preencher Vistas em seu código irá provavelmente exigir o uso de CGRectMake
um monte.Como o próprio nome diz, ele cria um retângulo que você pode usar para definir a posição relativa (em relação às fronteiras do seu superview) e o tamanho do seu UIView-Subclass
(neste caso, uma UILabel
).
Funciona assim:
yourLabel.Frame = CGRectMake(x, y, width, height); //x,y,width,height are float values.
x
define o espaçamento entre a mão esquerda fronteira do superview e o início de visualização secundária seu acrescentar, mesmo se aplica para y
mas relacionados com o espaçamento entre os top-fronteira de seu superview.em seguida, largura e altura são auto-explicativas, eu acho.
Espero que isso coloca você na pista.
Outras dicas
Em vez de encontrar uma maneira de contar a vista de onde posicionar o UILabel, você pode dizer o UILabel onde posicionar em modo de exibição usando o "centro".
E. g.
myLabel.center = CGPointMake(0.0, 0.0);
Espero que você vai ser capaz de usar UILabel, para mim é a forma básica de uma flexível não de texto editável.
Para Swift:
let yourLabel = UILabel(frame: CGRectMake(100, 100, 100, 100))
yourLabel.textColor = UIColor.whiteColor()
yourLabel.backgroundColor = UIColor.blackColor()
yourLabel.text = "mylabel text"
yoursuperview.addSubview(yourLabel)
Esta questão é antiga, mas de um puro a uiview opção de texto sem usar UILabel ou UITextField (como todas as outras respostas descrever, mas a questão é como fazer isso sem eles), drawRect em uma subclasse a uiview trabalha para mim.Assim:
- (void)drawRect:(CGRect)rect{
NSString *string = @"Hello World!";
[string drawAtPoint:CGPointMake(100, 100) withFont:[UIFont boldSystemFontOfSize:16.0]];
}
Esta rotina apresenta um texto em uma posição X-Y
-(void)placeText:(NSString *)theText:(int)theX:(int)theY {
UILabel *textLabel;
// Set font and calculate used space
UIFont *textFont = [UIFont fontWithName:@"Helvetica" size:14];
CGSize textStringSize = [theText sizeWithFont:textFont constrainedToSize:CGSizeMake(300,50) lineBreakMode:NSLineBreakByTruncatingTail];
// Position of the text
textLabel = [[UILabel alloc] initWithFrame:CGRectMake(theX+OFFSETIMAGEX-(textStringSize.width/2), theY+OFFSETIMAGEY-(textStringSize.height/2), textStringSize.width,textStringSize.height)];
// Set text attributes
textLabel.textColor = [UIColor blackColor];
textLabel.backgroundColor = [UIColor orangeColor];
textLabel.font = textFont;
textLabel.text = theText;
// Display text
[self.view addSubview:textLabel];
}
Pode ser atrasado mas aqui está o que eu uso:-
CGRect labelFrame = CGRectMake(120,300, 530, 100);
UILabel *myLabel = [[UILabel alloc] initWithFrame:labelFrame];
//If you need to change the color
[myLabel setTextColor:[UIColor whiteColor]];
//If you need to change the system font
[myLabel setFont:[UIFont fontWithName:NULL size:23]];
//If you need alignment
[myLabel setTextAlignment:NSTextAlignmentCenter];
// The label will use an unlimited number of lines
[myLabel setNumberOfLines:0];
//Add label view to current view
[self.view addSubview:myLabel];
NSString *someString = @"Sample String, Yarp!";
myLabel.text = someString;
adicionar um UILabel para o Visualizar.em seguida, substituir o modo de Exibição do layoutSubviews método.