2013-03-22 14 views
26

Attualmente ho un bordo normale. Vorrei avere solo un bordo superiore e inferiore.UITextField solo bordo superiore e inferiore

Come posso realizzare questo?

Utilizzando il UITextField 's proprietà layer, ho il seguente codice:

self.layer.borderColor = [[UIColor colorWithRed:160/255.0f green:160/255.0f blue:160/255.0f alpha:1.0f] CGColor]; 
    self.layer.borderWidth = 4.0f; 

Ho tipo di ottenuto al lavoro in fare il mio UITextField extra lungo, in modo che l'utente non vede il frontiere sinistra e destra, ma mi stavo chiedendo se c'era un modo migliore e meno hacker di farlo?

ho controllato la documentazione, e modificare una s borderStyleUITextField' non ha questa opzione.

Da,

Un iOS First Timer

+0

questo dovrebbe dare un buon inizio: http: // StackOverflow .com/a/8197568/937822 – lnafziger

risposta

75

Un approccio che ho trovato funziona bene è l'utilizzo di livelli. Ecco uno snippet:

CALayer *bottomBorder = [CALayer layer]; 
bottomBorder.frame = CGRectMake(0.0f, self.frame.size.height - 1, self.frame.size.width, 1.0f); 
bottomBorder.backgroundColor = [UIColor blackColor].CGColor; 
[myTextField.layer addSublayer:bottomBorder]; 

Spero che questo aiuti qualcuno.

+0

Questo non funziona su iOS 7. Visualizza un bordo inferiore in più, ma mantiene il lato e le linee superiori. – Peterdk

+0

@Peterdk, funzionerà, se si è passato sopra il codice in viewDidAppears (animato). – John

9

è possibile creare un'immagine che, con bordo superiore e inferiore e impostarlo per lo sfondo del vostro UITextField:

yourTextField.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"yourBorderedImageName"]]; 
+0

Hmm ... anche questo sembra abbastanza hacker, sono sorpreso che non ci sia modo di usare lo stile di frontiera o qualcosa di più semplice per fare questo, vedrò quello che gli altri hanno da dire, forse potrebbero sapere un modo migliore: – GangstaGraham

+0

sì, ho avuto lo stesso problema e alla fine sono uscito con questa opzione. – KDeogharkar

+0

Funziona se il tuo UITextFie L'altezza o la larghezza di ld cambia? – Dean

1

io ti suggerisce posiziona una vista sul lato sinistro del campo di testo e una vista sul lato destro del campo di testo per coprire il bordo sinistro/destro.

UIView *v1 = [[UIView all] initWithFrame:CGRectMake(textfield.frame.origin.x - 5, textfield.frame.origin.y, 10, textifield.frame.size.height)]; 
UIView *v2 = [[UIView all] initWithFrame:CGRectMake(textfield.frame.origin.x + textfield.frame.size.with - 5, textfield.frame.origin.y, 10, textifield.frame.size.height)]; 
5

È inoltre possibile aggiungere viste in alto e in basso da utilizzare come bordi.

// Top border 
UIView *topBorder = [[UIView alloc] 
    initWithFrame:CGRectMake(0, 
          0, 
          textfield.frame.size.width, 
          4.0f)]; 
topBorder.backgroundColor = [UIColor colorWithRed:160/255.0f 
              green:160/255.0f 
              blue:160/255.0f 
              alpha:1.0f]; 
[textfield addSubview:topBorder]; 

// Bottom border 
UIView *bottomBorder = [[UIView alloc] 
    initWithFrame:CGRectMake(0, 
          textfield.frame.origin.y + 
           textfield.frame.size.height - 4.0f, 
          textfield.frame.size.width, 
          4.0f)]; 
bottomBorder.backgroundColor = [UIColor colorWithRed:160/255.0f 
               green:160/255.0f 
               blue:160/255.0f 
               alpha:1.0f]; 
[textfield addSubview:bottomBorder]; 
+2

Eccellente, grazie per l'idea. Solo una nota: dato che stai aggiungendo il bordo come sottoview di UITextField, probabilmente non vuoi posizionare il bordo in base all'origine del campo di testo poiché si riferisce allo spazio delle coordinate del suo genitore. Volete che il bordo superiore inizi da (0,0) e il fondo inizi a: (textfield.frame.size.height - 4.0f) – TylerJames

4

È possibile utilizzare i livelli per aggiungere linee/forme per qualsiasi sottoclasse UIView. Questo codice disegna due linee nella parte superiore e inferiore di un campo di testo. È possibile aggiungerlo a una sottoclasse di un controllo o chiamarlo direttamente in un controller di visualizzazione/visualizzazione padre.

CGRect layerFrame = CGRectMake(0, 0, _usernameField.frame.size.width, _usernameField.frame.size.height); 
CGMutablePathRef path = CGPathCreateMutable(); 
CGPathMoveToPoint(path, NULL, 0, 0); 
CGPathAddLineToPoint(path, NULL, layerFrame.size.width, 0); // top line 
CGPathMoveToPoint(path, NULL, 0, layerFrame.size.height); 
CGPathAddLineToPoint(path, NULL, layerFrame.size.width, layerFrame.size.height); // bottom line 
CAShapeLayer * line = [CAShapeLayer layer]; 
line.path = path; 
line.lineWidth = 2; 
line.frame = layerFrame; 
line.strokeColor = [UIColor blackColor].CGColor; 
[_usernameField.layer addSublayer:line]; 
+0

Qual è l'impatto sulle prestazioni per disegnare la linea anziché aggiungere una sottoview? – Zorayr

+0

@Zorayr Un livello sembra un oggetto piuttosto semplice rispetto a un UIView quindi, a un'ipotesi calcolata, ritengo che i livelli sarebbero molto più performanti. – Ger

+1

Solo un'osservazione utile. Se questo codice viene aggiunto al controllore della vista genitore, le linee non cambieranno la loro lunghezza quando il dispositivo cambia orientamento. Per gestire questo (ed evitare la sottoclasse), ho reso a CAShapeLayer l'immagine e l'ho usata come sfondo per il campo di testo. Codice per il rendering dell'immagine: UIGraphicsBeginImageContextWithOptions (textField.bounds.size, textField.opaque, 0.0); [line renderInContext: UIGraphicsGetCurrentContext()]; UIImage * image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); [textField setBackground: image]; – Yarlik

39

@ grande & semplice esempio di user3075378 a Swift

var bottomBorder = CALayer() 
bottomBorder.frame = CGRectMake(0.0, textField.frame.size.height - 1, textField.frame.size.width, 1.0); 
bottomBorder.backgroundColor = UIColor.blackColor().CGColor 
textField.layer.addSublayer(bottomBorder) 
+11

@kareem perché? La domanda è contrassegnata come obiettivo-c e viene anche utilizzata nella domanda. – bobbaluba

+13

Perché potrebbero esserci più persone con lo stesso problema che utilizzano Swift invece di Objective-C. Ad esempio, sono felice che l'abbia pubblicato su Swift – Emptyless

22

@Sebyddd perché fermarsi qui? (;

EDIT: C'è un problema con le linee in fase di elaborazione prima di layout automatico imposta la giusta cornice per la vista, ho modificato la mia risposta con una correzione: Si tratta fondamentalmente chiamando drawLines() in layoutSubviews():

class FramedTextField: UITextField { 

    @IBInspectable var linesWidth: CGFloat = 1.0 { didSet{ drawLines() } } 

    @IBInspectable var linesColor: UIColor = UIColor.blackColor() { didSet{ drawLines() } } 

    @IBInspectable var leftLine: Bool = false { didSet{ drawLines() } } 
    @IBInspectable var rightLine: Bool = false { didSet{ drawLines() } } 
    @IBInspectable var bottomLine: Bool = false { didSet{ drawLines() } } 
    @IBInspectable var topLine: Bool = false { didSet{ drawLines() } } 



    func drawLines() { 

     if bottomLine { 
      add(CGRectMake(0.0, frame.size.height - linesWidth, frame.size.width, linesWidth)) 
     } 

     if topLine { 
      add(CGRectMake(0.0, 0.0, frame.size.width, linesWidth)) 
     } 

     if rightLine { 
      add(CGRectMake(frame.size.width - linesWidth, 0.0, linesWidth, frame.size.height)) 
     } 

     if leftLine { 
      add(CGRectMake(0.0, 0.0, linesWidth, frame.size.height)) 
     } 

    } 

    typealias Line = CGRect 
    private func add(line: Line) { 
     let border = CALayer() 
     border.frame = line 
     border.backgroundColor = linesColor.CGColor 
     layer.addSublayer(border) 
    } 

    override func layoutSubviews() { 
     super.layoutSubviews() 
     drawLines() 
    } 

} 
+0

Sono nuovo all'obiettivo c e ho difficoltà a creare una lezione, puoi provare a spiegare come posso farlo? Grazie in anticipo –

+0

@RicardoAlves in Xcode, a sinistra in 'Project Navigator' (dove sono tutti i file) tasto destro del mouse>' Nuovo file'> in iOS selezionare 'Fonte'>' Cocoa Touch Class'> premere 'Avanti' su inserisci il nome della classe, il genitore, ecc. –

+1

Questa dovrebbe essere la risposta accettata. Senza supporto per il layout automatico, è un prototipo. –

1

Spero che questo aiuti, mettere questo all'interno di una classe campo di testo di sostituzione

UIView *view = [[UIView alloc] init]; 
     view.translatesAutoresizingMaskIntoConstraints = NO; 
     view.layer.borderWidth = 1; 
     view.backgroundColor = [UIColor blackColor]; 
     [self addSubview:view]; 

     [self addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]]; 
     [self addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0.0]]; 
     [self addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1.0 constant:1.0]]; 
     [self addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:1.0]]; 
0

Grazie al user3075378. la mia risposta si basa sulla sua. destra ea sinistra l'aggiunta di piccole linee.

- (void)styleSearchTextField { 
    CALayer *bottomBorder = [CALayer layer], *leftBorder = [CALayer layer], *rightBorder = [CALayer layer]; 

    CGFloat thickness = 1.0f; 
    CGFloat side_height = 6.0f; 

    bottomBorder.frame = CGRectMake(0.0f, searchTextField.frame.size.height - 1, searchTextField.frame.size.width, thickness); 

    leftBorder.frame = CGRectMake(0.0f, searchTextField.frame.size.height - side_height, thickness, searchTextField.frame.size.height - 1); 

    rightBorder.frame = CGRectMake(searchTextField.frame.size.width - 1, searchTextField.frame.size.height - side_height, thickness, searchTextField.frame.size.height - 1); 

    bottomBorder.backgroundColor = [self.stylingDetails themeGrayColor].CGColor; 
    leftBorder.backgroundColor = [self.stylingDetails themeGrayColor].CGColor; 
    rightBorder.backgroundColor = [self.stylingDetails themeGrayColor].CGColor; 

    [searchTextField.layer addSublayer:bottomBorder]; 
    [searchTextField.layer addSublayer:leftBorder]; 
    [searchTextField.layer addSublayer:rightBorder]; 
} 
2

Swift 3: Pulire con layout automatico (sto usando qui PureLayout ma si può anche farlo con NSLayoutConstraint comune:

func makeUnderline(for textField: UITextField) { 
    let borderLine = UIView() 
    borderLine.backgroundColor = UIColor.black 
    borderLine.autoSetDimension(.height, toSize: 1) 
    textField.addSubview(borderLine) 
    borderLine.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets.zero, excludingEdge: .top) 
} 
Problemi correlati