Narysuj linię w UIView

Muszę narysować poziomą linię w UIView. Jak najłatwiej to zrobić. Na przykład chcę narysować czarną poziomą linię przy y-coord=200.

Nie używam Interface Builder.

Author: Andrew Vergunov, 2010-06-28

8 answers

Najprostszym sposobem w Twoim przypadku (linia pozioma) jest dodanie subview z czarnym kolorem tła i ramką [0, 200, 320, 1].

Przykład kodu (mam nadzieję, że nie ma błędów-napisałem go bez Xcode):

UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 200, self.view.bounds.size.width, 1)];
lineView.backgroundColor = [UIColor blackColor];
[self.view addSubview:lineView];
[lineView release];
// You might also keep a reference to this view 
// if you are about to change its coordinates.
// Just create a member and a property for this...

Innym sposobem jest stworzenie klasy, która będzie rysować linię w swojej metodzie drawRect (możesz zobaczyć mój przykład kodu dla tego tutaj).

 119
Author: Michael Kessler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:20

Może to trochę za późno, ale chcę dodać, że jest lepszy sposób. Korzystanie z UIView jest proste, ale stosunkowo powolne. Ta metoda nadpisuje sposób rysowania widoku i jest szybsza:

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);

    // Draw them with a 2.0 stroke width so they are a bit more visible.
    CGContextSetLineWidth(context, 2.0f);

    CGContextMoveToPoint(context, 0.0f, 0.0f); //start at this point

    CGContextAddLineToPoint(context, 20.0f, 20.0f); //draw to this point

    // and now draw the Path!
    CGContextStrokePath(context);
}
 307
Author: b123400,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-23 17:35:14

Swift 3 i Swift 4

W ten sposób możesz narysować szarą linię na końcu widoku (ten sam pomysł, co odpowiedź b123400)
class CustomView: UIView {

    override func draw(_ rect: CGRect) {
        super.draw(rect)

        if let context = UIGraphicsGetCurrentContext() {
            context.setStrokeColor(UIColor.gray.cgColor)
            context.setLineWidth(1)
            context.move(to: CGPoint(x: 0, y: bounds.height))
            context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
            context.strokePath()
        }
    }
}
 19
Author: Guy Daher,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-21 14:15:12

Wystarczy dodać etykietę bez tekstu i z kolorem tła. Ustaw Współrzędne do wyboru, a także wysokość i szerokość. Możesz to zrobić ręcznie lub za pomocą narzędzia Interface Builder.

 14
Author: Phanindra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-19 12:41:51

Możesz użyć klasy UIBezierPath dla tego:

I może narysować tyle linii, ile chcesz:

Podklasowałem UIView :

    @interface MyLineDrawingView()
    {
       NSMutableArray *pathArray;
       NSMutableDictionary *dict_path;
       CGPoint startPoint, endPoint;
    }

       @property (nonatomic,retain)   UIBezierPath *myPath;
    @end

I zainicjalizował obiekty pathArray i dictPAth, które będą używane do rysowania linii. Piszę główną część kodu z własnego projektu:

- (void)drawRect:(CGRect)rect
{

    for(NSDictionary *_pathDict in pathArray)
    {
        [((UIColor *)[_pathDict valueForKey:@"color"]) setStroke]; // this method will choose the color from the receiver color object (in this case this object is :strokeColor)
        [[_pathDict valueForKey:@"path"] strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
    }

    [[dict_path objectForKey:@"color"] setStroke]; // this method will choose the color from the receiver color object (in this case this object is :strokeColor)
    [[dict_path objectForKey:@"path"] strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];

}

Metoda dotykowa:

UITouch *touch = [touches anyObject];
startPoint = [touch locationInView:self];
myPath=[[UIBezierPath alloc]init];
myPath.lineWidth = currentSliderValue*2;
dict_path = [[NSMutableDictionary alloc] init];

Metoda TouchesMoved:

UITouch *touch = [touches anyObject];
endPoint = [touch locationInView:self];

 [myPath removeAllPoints];
        [dict_path removeAllObjects];// remove prev object in dict (this dict is used for current drawing, All past drawings are managed by pathArry)

    // actual drawing
    [myPath moveToPoint:startPoint];
    [myPath addLineToPoint:endPoint];

    [dict_path setValue:myPath forKey:@"path"];
    [dict_path setValue:strokeColor forKey:@"color"];

    //                NSDictionary *tempDict = [NSDictionary dictionaryWithDictionary:dict_path];
    //                [pathArray addObject:tempDict];
    //                [dict_path removeAllObjects];
    [self setNeedsDisplay];

Metoda Dotykowa:

        NSDictionary *tempDict = [NSDictionary dictionaryWithDictionary:dict_path];
        [pathArray addObject:tempDict];
        [dict_path removeAllObjects];
        [self setNeedsDisplay];
 11
Author: Rakesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-24 06:32:52

Jedna inna (i jeszcze krótsza) możliwość. Jeśli jesteś wewnątrz drawRect, coś w stylu:

[[UIColor blackColor] setFill];
UIRectFill((CGRect){0,200,rect.size.width,1});
 11
Author: hkatz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-27 01:42:53

Na podstawie odpowiedzi Guya Dahera.

Staram się unikać używania ? ponieważ może to spowodować awarię aplikacji, Jeśli GetCurrentContext () zwróci nil.

Zrobiłbym nil check if:

class CustomView: UIView 
{    
    override func draw(_ rect: CGRect) 
    {
        super.draw(rect)
        if let context = UIGraphicsGetCurrentContext()
        {
            context.setStrokeColor(UIColor.gray.cgColor)
            context.setLineWidth(1)
            context.move(to: CGPoint(x: 0, y: bounds.height))
            context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
            context.strokePath()
        }
    }
}
 0
Author: Robert Harrold,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-02 17:36:56

Dodaj etykietę bez tekstu i z kolorem tła odpowiadającym rozmiarowi ramki(np. wysokość=1). Zrób to za pomocą kodu lub w kreatorze interfejsów.

 -1
Author: Reddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-02 17:46:30